Skip to content

Commit 681218b

Browse files
author
Joseph Luce
authored
Create 300_longest_increasing_subsequence.md
1 parent 474b0a8 commit 681218b

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# 300. Longest Increasing Subsequence
2+
3+
## Iterative Solution
4+
- Runtime: O(N^2)
5+
- Space: O(N)
6+
- N = Number of elements in array
7+
8+
If we were to start from the left to the right, we would have seen the longest subsequence on the left side as we are going to the right.
9+
Inorder for us to know what those longest subsequences were, we will need a way to store that, hello dynamic programming.
10+
11+
For each element, we would need look at the numbers less than the current element on the left side.
12+
Now that we know which numbers are those, we can look at their corresponding longest subsequence the in dynamic programming array.
13+
This will tell us what to set as our longest subsequence for this current element.
14+
15+
We are basically building the longest increasing subsequence from the bottom up.
16+
17+
**Example:**
18+
19+
I(Input): [10,9,2,5,3,7,101,18]
20+
21+
DP: [1,1,1,1,1,1,1,1]
22+
23+
1. DP[1] = 1 + max([]) **(I[1] not > I[0])**
24+
2. DP[2] = 1 + max([]) **(I[2] not > I[0],I[1])**
25+
3. DP[3] = 1 + max(DP[2]) **(I[3] > I[2] and I[3] not > I[0],I[1])**
26+
4. DP[4] = 1 + max(DP[2]) **(I[4] > I[2] and I[4] not > I[0],I[1],I[3])**
27+
5. DP[5] = 1 + max(DP[1], DP[2], DP[3]) **(I[5] > I[1],I[2],I[3] and I[5] not > I[0])**
28+
6. DP[6] = 1 + max(DP[0], DP[1], DP[2], DP[3], DP[4], DP[5]) **(I[6] > all prev numbers)**
29+
7. DP[7] = 1 + max(DP[0], DP[1], DP[2], DP[3], DP[4], DP[5]) **(I[7] > all prev numbers except I[6])**
30+
31+
```
32+
class Solution:
33+
def lengthOfLIS(self, nums: List[int]) -> int:
34+
dp = [1]*len(nums)
35+
for index in range(1, len(nums)): # skip first element
36+
dp[index] = 1 + max([dp[j] for j in range(index) if nums[index] > nums[j]], default=0)
37+
return max(dp, default=0)
38+
```

0 commit comments

Comments
 (0)