300. Longest Increasing Subsequence
/*
* @lc app=leetcode id=300 lang=cpp
*
* [300] Longest Increasing Subsequence
*
* https://leetcode.com/problems/longest-increasing-subsequence/description/
*
* algorithms
* Medium (56.61%)
* Likes: 21409
* Dislikes: 467
* Total Accepted: 2M
* Total Submissions: 3.5M
* Testcase Example: '[10,9,2,5,3,7,101,18]'
*
* Given an integer array nums, return the length of the longest strictly
* increasing subsequence.
*
*
* Example 1:
*
*
* Input: nums = [10,9,2,5,3,7,101,18]
* Output: 4
* Explanation: The longest increasing subsequence is [2,3,7,101], therefore
* the length is 4.
*
*
* Example 2:
*
*
* Input: nums = [0,1,0,3,2,3]
* Output: 4
*
*
* Example 3:
*
*
* Input: nums = [7,7,7,7,7,7,7]
* Output: 1
*
*
*
* Constraints:
*
*
* 1 <= nums.length <= 2500
* -10^4 <= nums[i] <= 10^4
*
*
*
* Follow up: Can you come up with an algorithm that runs in O(n log(n)) time
* complexity?
*
*/
// @lc code=start
class Solution {
public:
int lengthOfLIS(vector<int>& nums)
{
int n = nums.size();
vector<int> dp(n, 1);
for(int i = 1; i < n; i++)
{
for(int j = 0; j < i; j++)
{
if(nums[i] > nums[j])
{
dp[i] = max(dp[i], dp[j] + 1);
}
}
}
return *max_element(dp.begin(), dp.end());
}
};
// @lc code=end
-
T:
-
S:
-
Use lower_bound
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int n = nums.size();
if (nums.empty()) return 0;
vector<int> res;
res.push_back(nums[0]);
for (int i = 1; i < n; i++)
{
if (nums[i] > res.back())
{
res.push_back(nums[i]);
}
else
{
int j = lower_bound(res.begin(), res.end(), nums[i]) - res.begin();
res[j] = nums[i];
}
}
return res.size();
}
};
- T:
- S: