Created
August 14, 2017 00:24
-
-
Save sdpatil/4f8b3427d3f36c305d18d02050ea0fa4 to your computer and use it in GitHub Desktop.
Find the longest nondecreasing subsequence
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
import java.util.Collection; | |
import java.util.Collections; | |
import java.util.List; | |
/** | |
* Problem: Write a program that takes as input an array of numbers and returns the length of a longest nondecreasing/increasing | |
* subsequence in the array | |
*/ | |
public class FindLongestNonDecreasingSubsequence { | |
/* | |
Basic idea is create a temporary 1 dimension array of same length as that of A. Initialize all its fields to 1 | |
because every element is 1 length array of increasing element | |
In second step | |
*/ | |
public int longestNonDecreasingSubsequenceLength(List<Integer> A){ | |
Integer[] longestSubsequenceArray = new Integer[A.size()]; | |
//Initialize every element to 1 | |
Arrays.fill(longestSubsequenceArray,1); | |
// Create a loop from 1 to length of A, and second loop of j = 0 to j < i. Check if the element at i is | |
// greater than element at j if yes set longestSubsequenceArray[i] = Math.max(longestSubsequenceArray[i], longestSubsequenceArray[j]+1) | |
for(int i = 1; i < A.size() ;i++ ){ | |
for(int j = 0; j < i; j++){ | |
if(A.get(i) > A.get(j)){ | |
longestSubsequenceArray[i] = Math.max(longestSubsequenceArray[i], longestSubsequenceArray[j]+1); | |
} | |
} | |
} | |
return Collections.max(Arrays.asList(longestSubsequenceArray)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment