|
| 1 | +package medium; |
| 2 | + |
| 3 | +import utils.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 | +public class LengthIncreasingSubsequence { |
| 22 | + public int lengthOfLIS(int[] nums) { |
| 23 | + if(nums == null || nums.length == 0) return 0; |
| 24 | + |
| 25 | + int[][] dp = new int[nums.length][nums.length]; |
| 26 | + int max = 0; |
| 27 | + for(int i = 0; i < nums.length; i++){ |
| 28 | + int currentMaxForThisRow = nums[i]; |
| 29 | + for(int j = 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(int k = 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 | + else dp[i][j] = dp[i][j-1]; |
| 50 | + } |
| 51 | + max = Math.max(max, dp[i][j]); |
| 52 | + } |
| 53 | + } |
| 54 | + CommonUtils.printMatrix(dp); |
| 55 | + return max; |
| 56 | + } |
| 57 | + |
| 58 | + public static void main(String...strings){ |
| 59 | + LengthIncreasingSubsequence test = new LengthIncreasingSubsequence(); |
| 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 = new int[]{1,3,6,7,9,4,10,5,6}; |
| 63 | + System.out.println(test.lengthOfLIS(nums)); |
| 64 | + } |
| 65 | +} |
0 commit comments