算法刷题记录 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;

    }
};
相关推荐
white-persist36 分钟前
【vulhub weblogic CVE-2017-10271漏洞复现】vulhub weblogic CVE-2017-10271漏洞复现详细解析
java·运维·服务器·网络·数据库·算法·安全
汀、人工智能36 分钟前
[特殊字符] 第9课:三数之和
数据结构·算法·数据库架构·图论·bfs·三数之和
汀、人工智能37 分钟前
[特殊字符] 第10课:接雨水
数据结构·算法·数据库架构·图论·bfs·接雨水
辰痕~39 分钟前
数据结构-第一节课
数据结构
故事和你911 小时前
蓝桥杯-2025年C++B组国赛
开发语言·软件测试·数据结构·c++·算法·职场和发展·蓝桥杯
py有趣1 小时前
力扣热门100题之合并区间
算法·leetcode
派大星~课堂1 小时前
【力扣-138. 随机链表的复制 ✨】Python笔记
python·leetcode·链表
cpp_25011 小时前
P10108 [GESP202312 六级] 闯关游戏
数据结构·c++·算法·动态规划·题解·洛谷·gesp六级
Lzh编程小栈1 小时前
数据结构与算法之队列深度解析:循环队列+C 语言硬核实现 + 面试考点全梳理
c语言·开发语言·汇编·数据结构·后端·算法·面试
AbandonForce1 小时前
模拟实现vector
开发语言·c++·算法