力扣-数组-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;
    }
};
相关推荐
倒头就睡的小比特5 天前
算法竞赛C++常用的STL
c++·算法
小羊没烦恼!5 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
猎头南楼5 天前
知识社区推荐系统实践:新用户冷启动与长短期兴趣建模的挑战 资深推荐算法工程师
人工智能·深度学习·算法·机器学习
旖旎夜光5 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
wzdark5 天前
大规模并行计算中的负载均衡算法研究4
算法
Because_of_Her15 天前
并查集-听课笔记
笔记·算法·并查集
码流子5 天前
高速公路安全监测实践:碰撞监测预警+物联网底座,从感知到处置的闭环
大数据·人工智能·物联网·算法·架构
another heaven5 天前
【算法/C++ MD5算法能否逆解码?原理、C++实现与同类哈希算法对比】
c++·算法·哈希算法
wzdark5 天前
从算法设计模式看编程思维的抽象能力4
算法
2601_962218615 天前
万象生鲜系统称重自动多退少补算法解决生鲜非标品痛点
大数据·数据库·人工智能·python·算法