|
| 1 | +packagemedium; |
| 2 | + |
| 3 | +importutils.CommonUtils; |
| 4 | + |
| 5 | +/**300. Longest Increasing Subsequence QuestionEditorial Solution My Submissions |
| 6 | +Total Accepted: 38678 |
| 7 | +Total Submissions: 108774 |
| 8 | +Difficulty: Medium |
| 9 | +Given an unsorted array of integers, find the length of longest increasing subsequence. |
| 10 | +
|
| 11 | +For example, |
| 12 | +Given [10, 9, 2, 5, 3, 7, 101, 18], |
| 13 | +The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the length. |
| 14 | +
|
| 15 | +Your algorithm should run in O(n2) complexity. |
| 16 | +
|
| 17 | +Follow up: Could you improve it to O(n log n) time complexity? |
| 18 | +
|
| 19 | +Credits: |
| 20 | +Special thanks to @pbrother for adding this problem and creating all test cases.*/ |
| 21 | +publicclassLengthIncreasingSubsequence { |
| 22 | +publicintlengthOfLIS(int[]nums) { |
| 23 | +if(nums ==null ||nums.length ==0)return0; |
| 24 | + |
| 25 | +int[][]dp =newint[nums.length][nums.length]; |
| 26 | +intmax =0; |
| 27 | +for(inti =0;i <nums.length;i++){ |
| 28 | +intcurrentMaxForThisRow =nums[i]; |
| 29 | +for(intj =0;j <nums.length;j++){ |
| 30 | +if(j <=i)dp[i][j] =1; |
| 31 | +else { |
| 32 | +if(nums[j] >nums[i]) { |
| 33 | +if(nums[j] >currentMaxForThisRow) { |
| 34 | +dp[i][j] =dp[i][j-1]+1; |
| 35 | +currentMaxForThisRow =nums[j]; |
| 36 | + }else { |
| 37 | +dp[i][j] =dp[i][j-1]; |
| 38 | +//in this case, we need to figure out when should we update currentMaxForThisRow? |
| 39 | +for(intk =j-1;k >=0;k--){ |
| 40 | +if(nums[k] <nums[j]){ |
| 41 | +if(dp[i][k]+1 ==dp[i][j] &&nums[j-1] >nums[j]){ |
| 42 | +currentMaxForThisRow =nums[j]; |
| 43 | + } |
| 44 | +break; |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | +elsedp[i][j] =dp[i][j-1]; |
| 50 | + } |
| 51 | +max =Math.max(max,dp[i][j]); |
| 52 | + } |
| 53 | + } |
| 54 | +CommonUtils.printMatrix(dp); |
| 55 | +returnmax; |
| 56 | + } |
| 57 | + |
| 58 | +publicstaticvoidmain(String...strings){ |
| 59 | +LengthIncreasingSubsequencetest =newLengthIncreasingSubsequence(); |
| 60 | +// int[] nums = new int[]{10, 9, 2, 5, 3, 7, 101, 18}; |
| 61 | +// int[] nums = new int[]{10,9,2,5,3,4}; |
| 62 | +int[]nums =newint[]{1,3,6,7,9,4,10,5,6}; |
| 63 | +System.out.println(test.lengthOfLIS(nums)); |
| 64 | + } |
| 65 | +} |