Find Longest Increasing Subsequence Using Binary Search
💻 coding

Find Longest Increasing Subsequence Using Binary Search

1 min read 154 words
1 min read
ShareWhatsAppPost on X
  • 1The Longest Increasing Subsequence (LIS) problem aims to find a subsequence of sorted integers in strictly ascending order.
  • 2This approach utilizes binary search, achieving a time complexity of O(n log n) for efficiency.
  • 3The provided code demonstrates how to implement the LIS algorithm using arrays and binary search techniques.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The Longest Increasing Subsequence (LIS) problem aims to find a subsequence of sorted integers in strictly ascending order."

Find Longest Increasing Subsequence Using Binary Search

In this approach we will find longest increasing Subsequence using Binary Search. Time Complexity for this approach will be nlogn.

The task is to find the length of the longest subsequence in a given array of integers such that all elements of the subsequence are sorted in strictly ascending order. This is called the Longest Increasing Subsequence (LIS) problem.

public class LongestIncreasingSubsequenceBinarySearch {

	public static void main(String[] args) {
		int[] arr = new int[] {3, 4, -1, 5, 8, 2, 3, 12, 7, 9, 10};
		int[] tempArr = new int[arr.length];
		int[] resArr = new int[arr.length];
		int len=0;
		int tempArrLastIndex = 0;
		
		for(int i=0;i<arr.length;i++) {
			resArr[i]=-1;
		}
		
		for(int i=0;i<arr.length-1;i++) {
			if(arr[i+1]>arr[tempArr[tempArrLastIndex]]) {
				tempArrLastIndex++;
				tempArr[tempArrLastIndex]=i+1;
				len++;
				resArr[i+1]=tempArr[tempArrLastIndex-1];
			}
			else {
				for(int j=0;j<=tempArrLastIndex;j++) {
					if(arr[i+1]<arr[tempArr[j]]) {
						tempArr[j]=i+1;
						if(j==0)
							resArr[i+1]=0;
						else
							resArr[i+1]=tempArr[j-1];
						break;
					}
				}
			}
		}
		
		System.out.println("Increasing Subsequence : " + (len+1));
		int i = tempArr[tempArrLastIndex];
		while(resArr[i] != -1)
		{
			System.out.println(arr[i]);
			i = resArr[i];
		}

	}

}

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 12 July 2018 · 1 min read · 154 words

Part of AskGif Blog · coding

You might also like

Find Longest Increasing Subsequence Using Binary Search | AskGif Blog