Algo-Sim › Dynamic Programming
Longest Increasing Subsequence
Medium · Dynamic Programming · step through it in Java, Python and C++ on your own input
dp[i] is the longest increasing run ending at i: one more than the best dp[j] over earlier, smaller nums[j].
Problem
Given an integer array nums, return the length of its longest strictly increasing subsequence. A subsequence keeps the original order but may skip elements.
Constraints
- 1 ≤ nums.length ≤ 2500
- -10⁴ ≤ nums[i] ≤ 10⁴
- O(n²) passes; the follow-up asks for O(n log n)
Edge cases to test
- Strictly decreasing:
1 - All equal:
1(strictly increasing) - One element
Follow-up questions
- Can you do better than O(n²)?
- Patience sorting: keep the smallest tail of each length and binary search where each value goes: O(n log n).
- How do you rebuild the sequence?
- Store a parent index for each element (in either method) and walk back from the end of the longest run.
- What about counting the LIS?
- Keep (length, count) per index and add counts of equal-length predecessors (LC 673): O(n²).
Solution
Java
public int lengthOfLIS(int[] nums) {
int[] dp = new int[nums.length];
Arrays.fill(dp, 1);
int best = 1;
for (int i = 1; i < nums.length; i++) {
for (int j = 0; j < i; j++) {
if (nums[j] < nums[i]) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
best = Math.max(best, dp[i]);
}
return best;
}Python
def length_of_lis(nums):
dp = [1] * len(nums)
best = 1
for i in range(1, len(nums)):
for j in range(i):
if nums[j] < nums[i]:
dp[i] = max(dp[i], dp[j] + 1)
best = max(best, dp[i])
return bestC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int lengthOfLIS(vector<int> &nums) {
vector<int> dp(int(nums.size()));
fill(dp.begin(), dp.end(), 1);
int best = 1;
for (int i = 1; i < int(nums.size()); i++) {
for (int j = 0; j < i; j++) {
if (nums[j] < nums[i]) {
dp[i] = std::max(dp[i], dp[j] + 1);
}
}
best = std::max(best, dp[i]);
}
return best;
}
};
More Dynamic Programming problems
- Climbing Stairs: Recursion → Memo → Table (Easy)
- Min Cost Climbing Stairs (Easy)
- House Robber (Medium)
- House Robber II (Medium)
- Coin Change (Medium)
- Coin Change II (Medium)
- Perfect Squares (Medium)
- Combination Sum IV (Medium)
- Decode Ways (Medium)
- Maximum Product Subarray (Medium)
- Best Time to Buy and Sell Stock with Cooldown (Medium)
- Best Time to Buy and Sell Stock with Transaction Fee (Medium)
- Best Time to Buy and Sell Stock III (Hard)
- Word Break (Medium)
- Unique Paths (Medium)
- Unique Paths II (Medium)
- Minimum Path Sum (Medium)
- Maximal Square (Medium)
- Partition Equal Subset Sum (Medium)
- Target Sum (Medium)
- Longest Common Subsequence (Medium)
- Interleaving String (Medium)
- 0/1 Knapsack (Medium)
- Edit Distance (Medium)
- Distinct Subsequences (Hard)
- Longest Palindromic Substring (Medium)
- Palindromic Substrings (Medium)
- Longest Palindromic Subsequence (Medium)
- Predict the Winner (Medium)
- Stone Game (Medium)