add solution to longest-increasing-subsequence problem

pull/1283/head
mohameddhamed 2023-11-23 19:27:23 +01:00
parent d3c2184af8
commit 9e9947cc2e
1 changed files with 26 additions and 0 deletions

View File

@ -0,0 +1,26 @@
// Given int array, return length of longest increasing subsequence
// Ex. nums = [10,9,2,5,3,7,101,18] -> 4, [2,3,7,101]
// Time: O(n^2)
// Space: O(n)
#include <bits/stdc++.h>
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int n = nums.size();
vector<int> dp(n, 1);
int result = 1;
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (nums[j] < nums[i]) {
dp[i] = max(dp[i], dp[j] + 1);
}
}
result = max(result, dp[i]);
}
return result;
}
};