算法刷题记录 Day42

算法刷题记录 Day42

Date: 2024.04.09

lc 122. 买卖股票的最佳时机II

c++ 复制代码
// dp
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
        if(n == 1)  return 0;
        // dp[i]表示第i天的最大利润;
        // dp[i] = dp[i-1] + max(prices[i]-prices[i-1], 0);
        vector<int> dp(n, 0);
        for(int i=1; i<n; i++){
            dp[i] = dp[i-1] + max(prices[i]-prices[i-1], 0);
        }
        return dp[n-1];
    }
};

// 贪心
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int res = 0;
        // 只要比昨天涨了,昨天就买,今天就卖
        for(int i=1; i<prices.size(); i++){
            if(prices[i] > prices[i-1])
                res += (prices[i] - prices[i-1]);
        }
        return res;
    }
};

lc 121. 卖卖股票的最佳时机

c++ 复制代码
// 贪心
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        // 取后项-前项中的最大值。1.暴力ON^2.
        // 2.从左往右遍历。记录当前的最小值和当前值减去最小值的大小;
        // 3. dp[i] 表示在前i天中完成买入和卖出的最大利润;
        // dp[i] = 
        int n = prices.size();
        
        int cur_min = INT_MAX;
        int cur_res = 0;

        for(int i=0; i<n; i++){
            if(i > 0)
                cur_res = max(cur_res, prices[i] - cur_min);
            cur_min = min(prices[i], cur_min);
        }
        return cur_res;

    }
};
相关推荐
宝贝儿好15 分钟前
【强化学习实战】第十一章:Gymnasium库的介绍和使用(1)、出租车游戏代码详解(Sarsa & Q learning)
人工智能·python·深度学习·算法·游戏·机器学习
weixin_458872614 小时前
东华复试OJ二刷复盘2
算法
Charlie_lll4 小时前
力扣解题-637. 二叉树的层平均值
算法·leetcode
爱淋雨的男人4 小时前
自动驾驶感知相关算法
人工智能·算法·自动驾驶
wen__xvn4 小时前
模拟题刷题3
java·数据结构·算法
滴滴答滴答答4 小时前
机考刷题之 6 LeetCode 169 多数元素
算法·leetcode·职场和发展
圣保罗的大教堂4 小时前
leetcode 1980. 找出不同的二进制字符串 中等
leetcode
Neteen5 小时前
【数据结构-思维导图】第二章:线性表
数据结构·c++·算法
礼拜天没时间.5 小时前
力扣热题100实战 | 第25期:K个一组翻转链表——从两两交换到K路翻转的进阶之路
java·算法·leetcode·链表·递归·链表反转·k个一组翻转链表
Swift社区5 小时前
LeetCode 400 第 N 位数字
算法·leetcode·职场和发展