Home
DSA Visualizer
Dynamic Programming
Longest Increasing Subsequence
Longest Increasing Subsequence
The longest increasing subsequence (LIS) problem asks for the length of the longest strictly increasing subsequence of an integer array.
READY
0
1
2
3
4
5
nums
LIS
Initialize DP array with 1s. Each element ends an LIS of length 1 by default.
Next
Checking LIS ending at index 0 (Value: 10)
Array
Intuition
Imagine you are jumping across stepping stones in a river, but you can only jump to a stone that is higher than the one you are currently on. You want to make the maximum number of jumps.
Concept
Dynamic Programming (O(N²)):
Let dp[i] be the length of the longest increasing subsequence ending at index i. To calculate dp[i], we look at all previous indices j < i. If nums[j] < nums[i], we can extend the subsequence ending at j. So, dp[i] = max(dp[i], dp[j] + 1).
How it Works
Algorithm:
- Initialize
dparray of size N with 1s. - Iterate i from 1 to N-1.
- Inner loop j from 0 to i-1.
- If
nums[i] > nums[j], updatedp[i] = max(dp[i], dp[j] + 1). - The answer is the maximum value in the entire
dparray.
Step-by-Step Breakdown
Visualizing the 1D DP Array:
- Base State: Every element is an LIS of length 1 (itself).
- Extension: When we find a smaller previous element, we 'extend' its LIS.
- Result: The longest LIS isn't necessarily at the last index; it's the max of all
dpvalues.
When to Use
Applications:
- Analyzing trends (stock market).
- Optimization problems where order matters.
- Layering or stacking problems (e.g., Russian Doll Envelopes).
When NOT to Use
- Contiguous Subarray: For contiguous subarrays, use Kadane's or Sliding Window.
- Arbitrary Order: If original order doesn't matter, just Sort and remove duplicates.
How to Identify
"Find longest sequence... strictly increasing... original order".
Applying for software engineering roles? Free, no sign-up:
