Advertisement
Guest User

Untitled

a guest
Jul 21st, 2017
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 KB | None | 0 0
  1. import java.util.Arrays;
  2.  
  3. public class LongestSubsequence{
  4.  
  5. public static void longestForward(int[] input){
  6. int length = 1;
  7. int longest = 1;
  8. int [] currentSubsequence = new int [input.length];
  9. int [] longestSubsequence = new int [input.length];
  10.  
  11. //Two loops: outer loop iterates through elements of the array
  12. //and makes each one the starting index before executing inner loop */
  13. for (int i = 0; i < input.length-1; i++){
  14. currentSubsequence[i] = input[i];
  15.  
  16. //next loop iterates through all proceeding elements in the array
  17. //after the starting index
  18. for (int j = i+1; j < input.length; j++){
  19. //if the next element is greater than the previous element in the
  20. // subsequence array, it is appended to the array
  21. if(input[j] > currentSubsequence[j-1]){
  22. currentSubsequence[j]=input[j];
  23. length ++;
  24. }
  25. //otherwise the length of the subsequence is compared to the
  26. //longest so far, if it is bigger it sets the longest subsequence
  27. //to the current subsequence
  28. else if(input[j] < currentSubsequence[j-1]){
  29. if(length > longest){
  30. longest =length;
  31. longestSubsequence = currentSubsequence;
  32. }
  33. }
  34. }
  35. }
  36.  
  37. int[] finalArray = Arrays.copyOfRange(longestSubsequence, 0, length);
  38. System.out.println(Arrays.toString(finalArray));
  39. }
  40.  
  41. public static void main (String[] args){
  42. int [] x = {1,2,3,2,6};
  43. longestForward(x);
  44.  
  45. }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement