📝 Problem Details
- Title:
300. Longest Increasing Subsequence
- Link: https://leetcode.com/problems/longest-increasing-subsequence/
- Difficulty: Medium
- Tags/Categories: Dynamic-Programming
input array
nums
return the length of the longest strictly increasing subsequence subsequence: can remove elements so long as the order of the remaining elements stay the same
💡 Explanation of Solution
1. subproblem identification
- whats the longest subsequence ending at index i
2. use a bottom up approach as it will inform the result of future index values
3. dp state
- let dp[i] be the length of the longest increasing sequence that ends at index i
- base case: every element by itself has an increasing subsequence is 1 --> dp[i] = 1
4. transition formula
- to build dp[i] check all previous indicies j < i
- if nums[j] < nums[i] (increasing), then update dp[i]
- dp[i] = max(dp[i], dp[j]+1)
- final answer is max(dp[i]) for all i
⌛ Complexity Analysis
Time Complexity: O(n^2)
Space Complexity: O(n) for dp table
💻 Implementation of Solution
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int n = nums.size();
if(n == 0) return 0;
vector<int> dp(n, 1); // base case: every element is a subsequence of length 1
int maxLength = 1;
for(int i=1; i < n; i++) {
for(int j=0; j < i; j++) {
if(nums[j] < nums[i]) { // valid increasing sequence
dp[i] = max(dp[i], dp[j] + 1);
}
}
maxLength = max(maxLength, dp[i]); // track max LIS found
}
return maxLength;
}
};