How do I implement longest increasing subsequence in C++?

To implement the Longest Increasing Subsequence (LIS) in C++, we can use dynamic programming for an efficient solution. The core idea is to maintain an array where each element at index i represents the length of the longest increasing subsequence that ends with the element at index i.

Here's an example code for the Longest Increasing Subsequence algorithm in C++:

#include <iostream> #include <vector> #include <algorithm> using namespace std; int longestIncreasingSubsequence(vector<int> &nums) { if (nums.empty()) return 0; vector<int> dp(nums.size(), 1); for (int i = 1; i < nums.size(); ++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()); } int main() { vector<int> nums = {10, 9, 2, 5, 3, 7, 101, 18}; cout << "Length of Longest Increasing Subsequence is: " << longestIncreasingSubsequence(nums) << endl; return 0; }

longest increasing subsequence LIS dynamic programming C++ algorithm