Skip to content

Commit e566edf

Browse files
committed
Longest Increasing Subsequence
1 parent 138d6a8 commit e566edf

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/*
2+
Longest Increasing Subsequence
3+
==============================
4+
5+
Given an integer array nums, return the length of the longest strictly increasing subsequence.
6+
7+
A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].
8+
9+
Example 1:
10+
Input: nums = [10,9,2,5,3,7,101,18]
11+
Output: 4
12+
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
13+
14+
Example 2:
15+
Input: nums = [0,1,0,3,2,3]
16+
Output: 4
17+
18+
Example 3:
19+
Input: nums = [7,7,7,7,7,7,7]
20+
Output: 1
21+
22+
Constraints:
23+
1 <= nums.length <= 2500
24+
-104 <= nums[i] <= 104
25+
26+
Follow up: Can you come up with an algorithm that runs in O(n log(n)) time complexity?
27+
*/
28+
29+
class Solution
30+
{
31+
public:
32+
int memo[2502][2502];
33+
34+
int lis(vector<int> &A, int ci, int pi)
35+
{
36+
if (ci == A.size())
37+
return 0;
38+
int ans = 0;
39+
if (memo[pi + 1][ci + 1] != -1)
40+
return memo[pi + 1][ci + 1];
41+
if (pi == -1 || A[pi] < A[ci])
42+
{
43+
ans = max(ans, 1 + lis(A, ci + 1, ci));
44+
}
45+
ans = max(ans, lis(A, ci + 1, pi));
46+
return memo[pi + 1][ci + 1] = ans;
47+
}
48+
49+
int lengthOfLIS(vector<int> &A)
50+
{
51+
memset(memo, -1, sizeof memo);
52+
return lis(A, 0, -1);
53+
}
54+
};

Leetcode Daily Challenge/July-2021/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,4 @@
99
| 6. | [Reduce Array Size to The Half](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge-2021/608/week-1-july-1st-july-7th/3804/) | [cpp](./06.%20Reduce%20Array%20Size%20to%20The%20Half.cpp) |
1010
| 7. | [Kth Smallest Element in a Sorted Matrix](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge-2021/608/week-1-july-1st-july-7th/3805/) | [cpp](./07.%20Kth%20Smallest%20Element%20in%20a%20Sorted%20Matrix.cpp) |
1111
| 8. | [Maximum Length of Repeated Subarray](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge-2021/609/week-2-july-8th-july-14th/3807/) | [cpp](./08.%20Maximum%20Length%20of%20Repeated%20Subarray.cpp) |
12+
| 9. | [Longest Increasing Subsequence](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge-2021/609/week-2-july-8th-july-14th/3808/) | [cpp](./09.%20Longest%20Increasing%20Subsequence.cpp) |

0 commit comments

Comments
 (0)