diff --git a/algorithms/CPlusPlus/Arrays/longest-increasing-subsequence.cpp b/algorithms/CPlusPlus/Arrays/longest-increasing-subsequence.cpp new file mode 100644 index 000000000..bd398d21a --- /dev/null +++ b/algorithms/CPlusPlus/Arrays/longest-increasing-subsequence.cpp @@ -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 + +class Solution { +public: + int lengthOfLIS(vector& nums) { + int n = nums.size(); + vector 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; + } +}; diff --git a/algorithms/CPlusPlus/README.md b/algorithms/CPlusPlus/README.md index 064a599b2..6568e0e1e 100644 --- a/algorithms/CPlusPlus/README.md +++ b/algorithms/CPlusPlus/README.md @@ -4,6 +4,7 @@ - [Counting Inversions](Arrays/counting-inversions.cpp) - [Dutch Flag Algorithm](Arrays/dutch-flag-algo.cpp) +- [Longest Increasing Subsequence](Arrays/longest-increasing-subsequence.cpp) - [Left Rotation](Arrays/left-rotation.cpp) - [Max Subarray Sum](Arrays/max-subarray-sum.cpp) - [Shift Negatives](Arrays/shift-negatives.cpp)