Problem Statement
Given an integer array nums, return the length of the longest strictly increasing subsequence.
A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements.
Approach 1: Bottom-Up DP ($O(n^2)$)
- State:
dp[i]is the length of the longest increasing subsequence ending at indexi. - Base Case:
dp[i] = 1(Every element is a subsequence of length 1). - Transition: For each element
j < i, ifnums[i] > nums[j], thendp[i] = max(dp[i], dp[j] + 1).
Java Implementation
public int lengthOfLIS(int[] nums) {
if (nums.length == 0) return 0;
int[] dp = new int[nums.length];
Arrays.fill(dp, 1);
int maxLen = 1;
for (int i = 1; i < nums.length; i++) {
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j]) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
maxLen = Math.max(maxLen, dp[i]);
}
return maxLen;
}
Approach 2: Binary Search ($O(n \log n)$)
This advanced approach maintains a list of "tails" of all increasing subsequences.
- For each number:
- If it's larger than the largest tail, append it.
- Otherwise, find the smallest tail larger than it and replace it.
Complexity Analysis
- Time Complexity: $O(n^2)$ for DP, $O(n \log n)$ for Binary Search.
- Space Complexity: $O(n)$.
Interview Tips
- "Approach 1 is the standard DP way. Approach 2 is an optimized version that is often asked in senior-level interviews."