[自我记录]随想录刷题第四十六天 | 1143. 最长公共子序列, 1035. 不相交的线, 53. 最大子数组和

代码随想录算法打卡第四十六天, 新手自我记录一下刷题历程, 仅为自我打卡使用.


1143. 最长公共子序列

class Solution {
public:
    int longestCommonSubsequence(string text1, string text2) {
        vector> dp(text1.size() + 1, vector(text2.size() + 1, 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]);
                }
            }
        }
        return dp[text1.size()][text2.size()];
    }
};

1035. 不相交的线

class Solution {
public:
    int maxUncrossedLines(vector& nums1, vector& nums2) {
        vector> dp(nums1.size() + 1, vector(nums2.size() + 1, 0));
        for (int i = 1; i <= nums1.size(); ++i) {
            for (int j = 1; j <= nums2.size(); ++j) {
                if (nums1[i - 1] == nums2[j - 1]) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }
        return dp[nums1.size()][nums2.size()];
    }
};

53. 最大子数组和

class Solution {
public:
    int maxSubArray(vector& nums) {
        vector dp(nums.size(), 0);
        int result = nums[0];
        dp[0] = nums[0];
        for(int i = 1; i < nums.size(); i++) {
            if (dp[i - 1] < 0) {
                dp[i] = nums[i];
            } else {
                dp[i] = dp[i - 1] + nums[i];
            }
            if (dp[i] > result) result = dp[i];
        }
        return result;
    }
};

希望能再坚持一天!

你可能感兴趣的:(刷题打卡自我记录,算法,leetcode,c++)