cpp: add “300. Longest Increasing Subsequence”
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
489d931f11
commit
4340c17b03
1 changed files with 25 additions and 0 deletions
25
cpp/longest-increasing-subsequence.cpp
Normal file
25
cpp/longest-increasing-subsequence.cpp
Normal file
|
@ -0,0 +1,25 @@
|
||||||
|
#include <algorithm>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
class Solution {
|
||||||
|
public:
|
||||||
|
int lengthOfLIS(const std::vector<int> &nums) {
|
||||||
|
if (nums.empty()) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<int> dp(nums.size(), 1);
|
||||||
|
int m = 1;
|
||||||
|
|
||||||
|
for (auto i = 1u; i < nums.size(); ++i) {
|
||||||
|
for (auto j = 0u; j < i; ++j) {
|
||||||
|
if (nums[i] > nums[j]) {
|
||||||
|
dp[i] = std::max(dp[i], 1 + dp[j]);
|
||||||
|
m = std::max(m, dp[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return m;
|
||||||
|
}
|
||||||
|
};
|
Loading…
Reference in a new issue