【代码随想录】day32

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录


一、122买卖股票的最佳时机II

方法1:计算斜率大于0的线段的diffY

cpp 复制代码
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int res = 0;
        int buyPrice = prices.front();
        for (int i = 1; i < prices.size(); i ++) {
            if (prices[i] <= buyPrice) {
                buyPrice = prices[i];
                continue;
            }
            if (i + 1 < prices.size() && prices[i+1] > prices[i]) {
                continue;
            }
            res += prices[i] - buyPrice;
            if (i + 1 < prices.size()) buyPrice = prices[i+1];
        }
        return res;
    }
};

方法2:套摆动序列模版

cpp 复制代码
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int res = 0;
        if (prices.size() < 2) return res;
        //找拐点,记录上升段
        int preDiff = 0;
        int curDiff, buyPrice;
        for (int i = 1; i < prices.size(); i ++) {
            curDiff = prices[i] - prices[i-1];
            if (preDiff <= 0 && curDiff > 0) {
                buyPrice = prices[i-1];
                while (i < prices.size() && prices[i] > prices[i-1]) {
                    i ++;
                }
                res += prices[i-1] - buyPrice;
            }
        }
        return res;
    }
};

方法3:把总收益折算成每日收益,累加正利润

cpp 复制代码
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int res = 0;
        for (int i = 1; i < prices.size(); i ++) {
            res += max(0, prices[i] - prices[i-1]);
        }
        return res;
    }
};

二、55跳跃游戏

思路:找最大覆盖范围

cpp 复制代码
class Solution {
public:
    bool canJump(vector<int>& nums) {
        int cover = 0;
        for (int i = 0; i <= cover && i < nums.size(); i ++) {
            cover = max(cover, i + nums[i]);
        }
        return cover >= nums.size() - 1;
    }
};

三、45跳跃游戏II

cpp 复制代码
class Solution {
public:
    int jump(vector<int>& nums) {
        int res = 0;
        int cover = 0;
        int maxCover = 0;
        for (int i = 0; i <= cover && i < nums.size(); i ++) {
            if (i > maxCover) {
                res ++;
                maxCover = cover;
            }
            cover = max(cover, i + nums[i]);
        }
        return res;
    }
};

相关推荐
kyle~6 小时前
模型预测控制(MPC)
算法·机器人·控制·传感器
牢姐与蒯7 小时前
cpp算法之哈希
c++·算法·哈希算法
开开心心就好8 小时前
两张表格数据对比工具,不用写函数也能查
算法·spring·智能手机·pdf·电脑·intellij-idea·音视频
电科_银尘8 小时前
【大模型算法与工程 02】线性回归与逻辑回归:从损失函数到决策边界
算法·逻辑回归·线性回归
玄昌盛不会编程10 小时前
LeetCode——2243. 计算字符串的数字和
java·算法·leetcode
电科_银尘12 小时前
【大模型算法与工程 01】机器学习的问题定义:监督、无监督、自监督与强化学习
人工智能·算法·机器学习
电科_银尘12 小时前
【大模型算法与工程 05】分类、回归与排序指标:怎样评价一个模型
算法·分类·回归
罗西的思考1 天前
【轻量化复刻大模型 / KIMI K3】Multi-Token Prediction(MTP / EAGLE-3)(2)
人工智能·算法·机器学习
罗西的思考1 天前
【轻量化复刻大模型 / KIMI K3】Multi-Token Prediction(MTP / EAGLE-3)(1)
人工智能·算法·机器学习
武子康1 天前
H3-World 接入 Game Agent:谁来判断门真的打开了?
人工智能·算法·机器学习