[leetcode]309. Best Time to Buy and Sell Stock with Cooldown

[leetcode]309. Best Time to Buy and Sell Stock with Cooldown


Analysis

直男真可怕—— [每天刷题并不难0.0]

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:

You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)

Explanation:

动态规划~

Implement

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

下面这个做法是讨论区一个大神哒~空间复杂度直接降成O(1)了

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int buy = INT_MIN;
        int sell = 0;
        int pre_buy;
        int pre_sell = 0;
        for(int price:prices){
            pre_buy = buy;
            buy = max(pre_sell-price, buy);
            pre_sell = sell;
            sell = max(pre_buy+price, sell);
        }
        return sell;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/85230581