Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- public class LongestSubsequence{
- public static void longestForward(int[] input){
- int length = 1;
- int longest = 1;
- int [] currentSubsequence = new int [input.length];
- int [] longestSubsequence = new int [input.length];
- //Two loops: outer loop iterates through elements of the array
- //and makes each one the starting index before executing inner loop */
- for (int i = 0; i < input.length-1; i++){
- currentSubsequence[i] = input[i];
- //next loop iterates through all proceeding elements in the array
- //after the starting index
- for (int j = i+1; j < input.length; j++){
- //if the next element is greater than the previous element in the
- // subsequence array, it is appended to the array
- if(input[j] > currentSubsequence[j-1]){
- currentSubsequence[j]=input[j];
- length ++;
- }
- //otherwise the length of the subsequence is compared to the
- //longest so far, if it is bigger it sets the longest subsequence
- //to the current subsequence
- else if(input[j] < currentSubsequence[j-1]){
- if(length > longest){
- longest =length;
- longestSubsequence = currentSubsequence;
- }
- }
- }
- }
- int[] finalArray = Arrays.copyOfRange(longestSubsequence, 0, length);
- System.out.println(Arrays.toString(finalArray));
- }
- public static void main (String[] args){
- int [] x = {1,2,3,2,6};
- longestForward(x);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement