力扣-数组-121 买卖股票的最佳时机

代码

超内存了

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

二维变一维,不超内存,超时间了

cpp 复制代码
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int dp[prices.size()]; // i  ------  size()-1 最大的那一个 
        for(int i = 0;i < prices.size();i++){
            int last = 0;
            for(int j = i; j<prices.size();j++){
                if(i == j){
                    last = 0;
                }else{
                    int temp = max( max( max(0, prices[j]-prices[i]), last), prices[j]-prices[i+1]);
                    last = temp;
                }
            }
            dp[i] = last;
        }
        int res = 0;
        for(int i = 0; i< prices.size();i++){
            res = max(res, dp[i]);
        }
        return res;
    }
};

看了大佬的题解,才明白跟dp没啥关系,主要应用贪心了

最后附上基于此思想的代码

cpp 复制代码
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int minPrice = prices[0];
        int profit = 0;
        for(int i = 1; i < prices.size(); i++) {
            profit = max(profit , prices[i] - minPrice);
            if(prices[i] < minPrice){
                minPrice = prices[i];
            }
        }
        return profit;
    }
};
相关推荐
vibecoding日记18 小时前
双非如何快速入职字节等大厂大模型?真实案例分析:推理优化和投机解码
算法·求职·大模型工程师
yszaygr213821 小时前
Verilog参数化游程编码RLE模块
算法
望易21 小时前
刚设计的大模型架构-双域耦合认知框架
算法·架构
复杂网络1 天前
多个 Claude Code 与多个 Codex 协同工作:设计与实现方案
算法
HjhIron2 天前
面试常客:字符串算法从入门到进阶
算法·面试
吴佳浩2 天前
DeepSeek DSpark:Confidence-Scheduled Speculative Decoding 技术解析
人工智能·算法·deepseek
触底反弹2 天前
🧠 搞懂 Token,才算真正入门大模型——从分词原理到 Embedding 语义实战
javascript·人工智能·算法
vivo互联网技术2 天前
ICLR 2026 | 基于后验采样的图像恢复方法LearnIR:人脸去阴影、去雾
人工智能·算法·aigc
浮生望2 天前
JS字符串与回文算法:从包装类到双指针的面试进阶之路
javascript·算法
黄敬峰2 天前
面试必刷:从JS底层包装类到双指针,彻底搞懂字符串与回文算法
算法