174、【动态规划/贪心算法/滑动窗口】leetcode ——674. 最长连续递增序列:一题多解 (C++版本)

题目描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
原题链接:674. 最长连续递增序列

解题思路

(1)双指针滑动窗口

class Solution {
public:
    int findLengthOfLCIS(vector<int>& nums) {
        int n = nums.size();
        if(n <= 1)                  return n;
        
        int res = 1;
        for(int i = 0; i < n; i++) {
            int j = i;
            while(j + 1 < n && nums[j] < nums[j + 1]) {			// 寻找连续递增子序列
                j++;
            }
            res = max(res, j + 1 - i);							// 找到最长连续递增子序列
            i = j;
        }

        return res;
    }
};

(1)贪心算法

  • 局部最优解:相邻子序列满足nums[i - 1] < nums[i],满足的记录最新长度,不满足的更新新的起始下标重新记录。
  • 全局最优解:整体的最长子序列
class Solution {
public:
    int findLengthOfLCIS(vector<int>& nums) {        
        int n = nums.size(), res = 1, start = 0;        
        for(int i = 1; i < n; i++) {
            if(nums[i - 1] >= nums[i])
                start = i;
            res = max(res, i - start + 1);
        }

        return res;
    }
};

(2)动态规划

  • 动态规划五步曲:

(1)dp[i]含义: 从下标i往前的最长连续子序列长度。

(2)递推公式: dp[i] = dp[i - 1] + 1,每遇到一个连续的字符,就在上一个已有的最长子序列长度上加一。

(3)dp数组初始化: dp[i] = 1,自身最少为一个。

(4)遍历顺序: 从左到有。

(5)举例:
image.png

class Solution {
public:
    int findLengthOfLCIS(vector<int>& nums) {
        int n = nums.size(), res = 1;
        vector<int> dp(n + 1, 1);

        for(int i = 1; i < n; i++) {
            if(nums[i - 1] < nums[i]) {
                dp[i] = dp[i - 1] + 1;
            }
            res = max(res, dp[i]);
        }
        

        return res;
    }
};

参考文章:674. 最长连续递增序列

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

辰阳星宇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值