Cover image for Interview Classic 150 Questions P300 Longest Increasing Subsequence

Interview Classic 150 Questions P300 Longest Increasing Subsequence


Timeline

Timeline

2025-12-12

init

Dynamic Programming

Problem:

dp[i]=max(dp[j])(0j<i,nums[j]<nums[i])+1;dp[i] = max(dp[j])_{( 0 \le j < i , nums[j] < nums[i])} + 1;

12345678910111213141516171819202122232425262728293031
#include <vector>#include <algorithm>#include <climits>using std::vector;class Solution {    public:        int lengthOfLIS(vector<int> &nums)        {                // dp[i] is the length of the longest strictly increasing subsequence ending with nums[i]                // dp[i] = max{dp[j]}(nums[j]<nums[i] && j<i) + 1;                int i, j, n = nums.size();                int max_val = INT_MIN;                vector<int> dp(n, 1);                for (i = 0; i < n; i++) {                        max_val = INT_MIN;                        for (j = 0; j < i; j++) {                                if (nums[j] < nums[i]) {                                        max_val = std::max(max_val, dp[j]);                                }                        }                        if (max_val != INT_MIN) {                                dp[i] = max_val + 1;                        }else{                                dp[i] = 1;                        }                }                return *std::max_element(dp.begin(), dp.end());        }};

leetcode hot 100 rewrite

1234567891011121314151617181920212223
#include <vector>#include <algorithm>using std::vector;class Solution {    public:        int lengthOfLIS(vector<int> &nums)        {                                int i, j, n = nums.size();                // dp[i] represents the length of the longest increasing subsequence ending with nums[i]                vector<int> dp(n, 1);                for (i = 0; i < n; i++) {                        for (j = 0; j < i; j++) {                                if (nums[j] < nums[i])                                        dp[i] = std::max(dp[j] + 1, dp[i]);                        }                }                return *std::max_element(dp.begin(), dp.end());        }};
Loading comments…