[Code Random Notes] Day 53 Dynamic Programming 14 (Longest Common Subsequence, Disjoint Lines, Maximum Subsequence Sum)

first question 

LeetCode official website - the technology growth platform loved by geeks around the world

To compare the status between two strings/arrays, use two-dimensional dp to mark the status of the two comparisons, with the row nums1 and the column nums2.

Similar to the longest common substring

class Solution {
public:
    int longestCommonSubsequence(string text1, string text2) {
        vector<vector<int>> dp(text1.size() + 1, vector<int>(text2.size() + 1, 0));
        int maxLen = 0;
        for (int i = 1; i <= text1.size(); i++) {
            for (int j = 1; j <= text2.size(); j++) {
                if (text1[i - 1] == text2[j - 1]) {
                    dp[i][j] = dp[i-1][j-1] + 1;
                }
                else dp[i][j] = max(dp[i-1][j], dp[i][j-1]);//注意这一行,最长公共子串没有这一行
                if (dp[i][j] > maxLen) maxLen = dp[i][j];
            }
        }
        return maxLen;
    }
};

Question 2

LeetCode official website - the technology growth platform loved by geeks around the world 

Question 3

LeetCode official website - the technology growth platform loved by geeks around the world

 Be sure to remember to set the dp size and initialize dp. i starts from 1. What dp seeks is the maximum sum of subsequences ending with nums[i], and max dp[i] is what the question requires.

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        vector<int> dp(nums.size());
        dp[0] = nums[0];
        for (int i = 1; i < nums.size(); i++) {
            dp[i] = max(dp[i-1]+ nums[i], nums[i]);
        }
        int maxSum = *max_element(dp.begin(), dp.end());
        return maxSum;
    }
};

Guess you like

Origin blog.csdn.net/weixin_43785314/article/details/132676678