01
Problem Statement
Given an integer array nums, return the length of the longest strictly increasing subsequence (LIS). A subsequence is obtained by deleting some (or no) elements without changing the order of the remaining elements. "Strictly increasing" means nums[i] < nums[i+1] for consecutive elements in the subsequence.
- The subsequence does not need to be contiguous. For example, in
[10,9,2,5,3,7,101,18], one LIS is[2,3,7,101]with length 4. - There is an O(n²) DP solution and an O(n log n) solution using binary search + a "tails" array.
02
Key Observations
- Define
dp[i]= length of the longest strictly increasing subsequence ending at indexi(and includingnums[i]). Thendp[i] = 1 + max(dp[j])over allj < isuch thatnums[j] < nums[i]. If no suchjexists,dp[i] = 1. - The answer is
max(dp[0], ..., dp[n-1]). Eachdp[i]depends only on earlier indices, so we fill the table in order. - For O(n log n): maintain an array
tailswheretails[len]is the smallest ending value of an increasing subsequence of lengthlen+1; for eachnums[i], binary search to updatetails.
03
Approach
High-level (O(n²)): dp[i] = LIS length ending at i. For each i, look at all j < i with nums[j] < nums[i] and set dp[i] = 1 + max(dp[j]). Return max(dp).
Steps:
dp[i] = 1for alliinitially. Forifrom 0 to n-1: forjfrom 0 to i-1, ifnums[j] < nums[i], thendp[i] = max(dp[i], 1 + dp[j]).- Return
max(dp[0..n-1]).
04
Implementation
Java
public int lengthOfLIS(int[] nums) {
int n = nums.length;
if (n == 0) {
return 0;
}
int[] dp = new int[n];
int best = 1;
for (int i = 0; i < n; i++) {
dp[i] = 1;
for (int j = 0; j < i; j++) {
if (nums[j] < nums[i]) {
dp[i] = Math.max(dp[i], 1 + dp[j]);
}
}
best = Math.max(best, dp[i]);
}
return best;
}05
Test Cases
Example 1
Input
nums = [10,9,2,5,3,7,101,18]
Expected
4Explanation
LIS is [2,3,7,101].
06
Complexity Analysis
- Time: O(n^2). O(n log n) with patience sort / binary search.
- Space: O(n).
07
Follow-ups
- Reconstruct one LIS; count number of LIS.