代码随想录算法训练营第55天|300.最长递增子序列、674. 最长连续递增序列、718. 最长重复子数组

300.最长递增子序列

https://leetcode.cn/problems/longest-increasing-subsequence/

class Solution {
public:
    int lengthOfLIS(vector& nums) {
        //dp[i] 以i为终点的最大长度
        vector dp(nums.size() , 1);
        int result = 1;
        for (int i = 1; i < nums.size(); i++) {
            for (int j = i - 1; j >= 0; j--) {
                if (nums[j] < nums[i]) {
                    dp[i] = max(dp[i], dp[j] + 1);
                    result = max(result, dp[i]);
                }
            }
        }
        return result;
    }
};

674. 最长连续递增序列

https://leetcode.cn/problems/longest-continuous-increasing-subsequence/

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

718. 最长重复子数组

https://leetcode.cn/problems/maximum-length-of-repeated-subarray/

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

你可能感兴趣的:(算法)