leetcode 122 123 309 188 714 股票买卖 动态规划

这类问题有一个通法

https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iii/solution/yi-ge-tong-yong-fang-fa-tuan-mie-6-dao-gu-piao-wen/

 再说吧,该睡觉了

 

122

只要是增加的买就完事了

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int max = 0 ;
        if(prices.size() == 0) return 0;
        for(int i = 0 ; i < prices.size() -1; i++){
            if(prices[i+1] - prices[i] > 0){
                max += prices[i+1] - prices[i];
            }
        }
        return max;
    }
};

123

 

简单的思路;

因为限制了买卖间必须间隔,所以遍历一遍,构建状态,然后载遍历一遍就好了

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
        int result = 0;
        // right[i] 代表从 i 开始的 prices 序列,能赚的最大的钱
        vector<int> right = vector(n,0);
        int maxRight = 0;
        int resRight = 0;
        for(int i=n-1;i>=0;i--) {
            // 倒序遍历,动态规划得到 right 数组
            maxRight = max(prices[i], maxRight);
            right[i] = max(resRight, maxRight - prices[i]);
        }
        // 正序遍历,resLeft 代表截止到 i,prices 序列能赚的最大的钱
        int minLeft = INT_MAX;
        int resLeft = 0;
        for(int i=0;i<n;i++) {
            minLeft = min(prices[i], minLeft);
            resLeft = max(resLeft, prices[i] - minLeft);
            // resLeft + right[i] 代表以 i 为分割,两侧分别能赚到的钱的总和
            result = max(result, resLeft + right[i]);
        }
        return result;
    }
};

猜你喜欢

转载自www.cnblogs.com/lqerio/p/12081813.html
今日推荐