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

    }
};
相关推荐
顶点多余6 小时前
那些在算法中适合巩固的知识点---1
java·前端·算法
AI情绪识别开源7 小时前
检信 ALLEMOTION OS 加密打包可执行程序 — 全面测试报告版本: v1.3功能测试 / 性能测试 /
开发语言·数据结构·人工智能·功能测试
罗西的思考8 小时前
【Agentic RL / 强化学习框架】Molt 设计解读
人工智能·算法·机器学习
hahaha60168 小时前
HLS高层次综合设计技巧--C++类和模板
图像处理·人工智能·算法·计算机视觉
多弗朗皮卡丘9 小时前
算法详解4:买卖股票的最佳时机系列(上)
算法
维克兜率天11 小时前
【维克】动量指标家族:RSI、ROC、CCI、Momentum全面解析
python·算法
AI情绪识别开源12 小时前
检信 AI 智能推广平台(代号:JX-Promote)
人工智能·算法·erlang
老当益壮梁奶奶13 小时前
Linux软件编程学习笔记(八):进程间通信详解(1)
linux·c语言·笔记·学习·算法
不会就选b13 小时前
算法日常・每日刷题--<BFS拓扑排序>4
算法
不正经学生13 小时前
C语言动态内存管理(上):堆上的自由与责任
c语言·开发语言·c++·算法·面试