力扣-数组-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;
    }
};
相关推荐
.30-06Springfield34 分钟前
决策树(Decision tree)算法详解(ID3、C4.5、CART)
人工智能·python·算法·决策树·机器学习
我不是哆啦A梦35 分钟前
破解风电运维“百模大战”困局,机械版ChatGPT诞生?
运维·人工智能·python·算法·chatgpt
xiaolang_8616_wjl39 分钟前
c++文字游戏_闯关打怪
开发语言·数据结构·c++·算法·c++20
small_wh1te_coder1 小时前
硬件嵌入式学习路线大总结(一):C语言与linux。内功心法——从入门到精通,彻底打通你的任督二脉!
linux·c语言·汇编·嵌入式硬件·算法·c
挺菜的1 小时前
【算法刷题记录(简单题)002】字符串字符匹配(java代码实现)
java·开发语言·算法
凌肖战5 小时前
力扣网编程55题:跳跃游戏之逆向思维
算法·leetcode
黑听人5 小时前
【力扣 简单 C】70. 爬楼梯
c语言·leetcode
88号技师6 小时前
2025年6月一区-田忌赛马优化算法Tianji’s horse racing optimization-附Matlab免费代码
开发语言·算法·matlab·优化算法
ゞ 正在缓冲99%…6 小时前
leetcode918.环形子数组的最大和
数据结构·算法·leetcode·动态规划
Kaltistss7 小时前
98.验证二叉搜索树
算法·leetcode·职场和发展