Longest Increasing Subsequence
Longest Increasing Subsequence
Dynamic Programming
Problem Statement
Given an integer array nums
, return the length of the longest strictly increasing subsequence.
Example
Example 1:
Input:
10
9
2
5
3
7
101
18
LIS:
2
3
7
101
Length: 4
Solution
This problem can be solved using dynamic programming. We'll create a DP array, dp
, where dp[i]
represents the length of the longest increasing subsequence that ends at index i
.
We initialize the dp
array with all 1s, since each element itself is an increasing subsequence of length 1. Then, we iterate through the array and for each element nums[i]
, we iterate through the previous elements nums[j]
(where j < i
). If nums[i] > nums[j]
, it means we can potentially extend the subsequence ending at j
.
Algorithm Steps (DP)
- Create a DP array
dp
of the same size asnums
and fill it with 1s. - Iterate from
i = 1
ton-1
. - Iterate from
j = 0
toi-1
. - If
nums[i] > nums[j]
, updatedp[i] = max(dp[i], 1 + dp[j])
. - The final answer is the maximum value in the
dp
array.
Recurrence Relation
dp[i] = max(dp[i], 1 + dp[j])
10
nums[0]9
nums[1]2
nums[2]5
nums[3]3
nums[4]7
nums[5]101
nums[6]18
nums[7]DP Table (LIS length ending at index)
Step: 1 / 37
Longest Increasing Subsequence Solution