GeeksforGeeks » Algorithms
Largest monotonically increasing sequence in an array
(5 posts)-
Write code for finding length of largest monotonically increasing sequence in an array of integers. Optimize it (not the usual O(n) in worst case, but a better approach in average case).
-
Algo : Use divide and conquer.
If A=array of elements, N = number of elements in A,
Length of largest monotonically increasing sequence = max (
Length of largest monotonically increasing sequence in A[0..N/2],
Length of largest monotonically increasing sequence in A[N/2..N],
Length of largest monotonically increasing sequence across the divide A[0..N/2] - A[N/2..N] )To find Length of largest monotonically increasing sequence across the divide A[0..N/2] - A[N/2..N], scan A[0..N/2] from right to left and ensure that the numbers keep decreasing. Get the count of the length of decreasing numbers in the left subarray as lCount. Repeat procedure for scanning A[N/2..N] from left to right and ensure that the numbers keep increasing. Get the count of the length of increasing numbers in the left subarray as rCount. Len of seq across the 2 subarrays is lCount + rCount. So,
Length of largest monotonically increasing sequence = max (
Length of largest monotonically increasing sequence in A[0..N/2],
Length of largest monotonically increasing sequence in A[N/2..N],
lCount + rCount )Use recursion to solve items 1 and 2.
-
This is one of the standard Dynamic Programming Problems
-
As we would need to scan the array atleast once, the complexity cannot be less than O(n).
Reply
You must log in to post.