力扣-数组-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;
    }
};
相关推荐
geovindu15 小时前
python:DecisionTree
开发语言·后端·python·算法
geovindu17 小时前
python: Decision Tree Regressor
开发语言·后端·python·算法·决策树
AllData公司负责人19 小时前
实战二:AllData大模型与AI数据底座-数据传输平台-DBSyncer,搭建 Http 接口同步至 Doris,API 业务数据自动拉取入数仓
大数据·数据库·数据仓库·人工智能·算法·http·doris
武子康20 小时前
火系被选七成,就应该削弱吗?
人工智能·算法·机器学习
夜不会漫长21 小时前
C++:C++11特性
开发语言·c++·算法
秋天的怀念_David21 小时前
算法一千零一夜 · 第三十七夜 · 类型的过路费
java·程序人生·算法
xckkcxxck1 天前
Kaggle S6E10 冠军方案精读(二):245 个模型的合唱团,和一个只会“线性指挥“的老师
算法
饮水桶_T1 天前
Git笔记
开发语言·笔记·算法
指掀涛澜天下惊1 天前
强化学习进阶篇十四 DPO算法
深度学习·算法·机器学习·sft·预训练·dpo