力扣-数组-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;
    }
};
相关推荐
dapeng28703 分钟前
分布式系统容错设计
开发语言·c++·算法
qq_417695058 分钟前
代码热修复技术
开发语言·c++·算法
Liu628887 小时前
C++中的工厂模式高级应用
开发语言·c++·算法
AI科技星7 小时前
全尺度角速度统一:基于 v ≡ c 的纯推导与验证
c语言·开发语言·人工智能·opencv·算法·机器学习·数据挖掘
参.商.7 小时前
【Day41】143. 重排链表
leetcode·golang
条tiao条8 小时前
KMP 算法详解:告别暴力匹配,让字符串匹配 “永不回头”
开发语言·算法
干啥啥不行,秃头第一名8 小时前
C++20概念(Concepts)入门指南
开发语言·c++·算法
zzh940778 小时前
Gemini 3.1 Pro 硬核推理优化剖析:思维织锦、动态计算与国内实测
算法
2301_807367198 小时前
C++中的解释器模式变体
开发语言·c++·算法
愣头不青8 小时前
617.合并二叉树
java·算法