|
| 1 | +//Recursion - Brute force (TLE) |
| 2 | + |
| 3 | +class Solution { |
| 4 | + public int lengthOfLIS(int[] nums) { |
| 5 | + if(nums.length <= 1) return nums.length; |
| 6 | + return lis(nums, 0, -1); |
| 7 | + } |
| 8 | + |
| 9 | + private int lis(int[] nums, int currentInd, int prevInd) { |
| 10 | + |
| 11 | + if(currentInd == nums.length) return 0; |
| 12 | + int skip = lis(nums, currentInd + 1, prevInd); |
| 13 | + int select = -1; |
| 14 | + if(prevInd == -1 || nums[currentInd] > nums[prevInd]) { |
| 15 | + select = 1 + lis(nums, currentInd+1, currentInd); |
| 16 | + } |
| 17 | + |
| 18 | + return Math.max(skip, select); |
| 19 | + } |
| 20 | + |
| 21 | +} |
| 22 | + |
| 23 | +//Recursion + Memoization |
| 24 | + |
| 25 | +class Solution { |
| 26 | + public int lengthOfLIS(int[] nums) { |
| 27 | + int n = nums.length; |
| 28 | + if(n <= 1) return n; |
| 29 | + |
| 30 | + int[][] dp = new int[n][n+1]; |
| 31 | + |
| 32 | + for(int[] rows : dp) { |
| 33 | + Arrays.fill(rows, -1); |
| 34 | + } |
| 35 | + |
| 36 | + return lis(nums, 0, -1, dp); |
| 37 | + } |
| 38 | + |
| 39 | + private int lis(int[] nums, int currentInd, int prevInd, int[][] dp) { |
| 40 | + |
| 41 | + if(currentInd == nums.length) return 0; |
| 42 | + |
| 43 | + if(dp[currentInd][prevInd+1] != -1) return dp[currentInd][prevInd+1]; |
| 44 | + |
| 45 | + int skip = lis(nums, currentInd + 1, prevInd, dp); |
| 46 | + int select = -1; |
| 47 | + if(prevInd == -1 || nums[currentInd] > nums[prevInd]) { |
| 48 | + select = 1 + lis(nums, currentInd+1, currentInd, dp); |
| 49 | + } |
| 50 | + |
| 51 | + dp[currentInd][prevInd+1] = Math.max(skip, select); |
| 52 | + |
| 53 | + return dp[currentInd][prevInd+1]; |
| 54 | + } |
| 55 | + |
| 56 | +} |
| 57 | + |
| 58 | +//DP |
| 59 | + |
| 60 | +class Solution { |
| 61 | + public int lengthOfLIS(int[] nums) { |
| 62 | + int n = nums.length; |
| 63 | + if(n <= 1) return n; |
| 64 | + |
| 65 | + int[] dp = new int[n]; |
| 66 | + |
| 67 | + Arrays.fill(dp, 1); |
| 68 | + |
| 69 | + int maxLength = 0; |
| 70 | + |
| 71 | + for(int i = 1; i < n; i++) { |
| 72 | + for(int j = 0; j < i; j++) { |
| 73 | + if(nums[i] > nums[j]) { |
| 74 | + dp[i] = Math.max(dp[i], 1+dp[j]); |
| 75 | + } |
| 76 | + } |
| 77 | + maxLength = Math.max(maxLength, dp[i]); |
| 78 | + } |
| 79 | + |
| 80 | + return maxLength; |
| 81 | + } |
| 82 | + |
| 83 | +} |
0 commit comments