sahithyan/utils Skip to content

longestIncreasingSubsequence

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
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());
}

Finds the length of the longest subsequence where elements are in strictly increasing order. The subsequence doesn’t need to be contiguous. This algorithm has applications in patience sorting and box stacking problems.