zoukankan      html  css  js  c++  java
  • leetcode 309. Best Time to Buy and Sell Stock with Cooldown

    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)

    Example:
    
    prices = [1, 2, 3, 0, 2]
    maxProfit = 3
    transactions = [buy, sell, cooldown, buy, sell]
    

    思路:dp[i][0]代表第i天清仓能得到的最大值,dp[i][1]表示第i天持仓能得到的最大值。
    那么如果没有冷却期的话,dp[i][0]=max(dp[i-1][0],dp[i-1][1]+prices[i]),dp[i][1]=max(dp[i-1][1],dp[i-1][0]-prices[i]). 现在是有一天的冷却期,那么dp[i][1]=max(dp[i-1][1],dp[i-2][0]-prices[i]),即要保证今天持仓是由前天转移过来的。事实上前天dp[i-2][0]并不一定是清仓后的结果,也可能是根本没买,但(根本不买的这种情况)并不影响最后结果..

    class Solution {
    public:
        // 0
        int maxProfit(vector<int>& prices) {
            int n = prices.size();
            if (n == 0) return 0;
            vector<vector<int> > dp(n, vector<int>(2));
            int ans = 0;
            for (int i = 0; i < n; ++i) {
                if (i == 0) {
                    dp[i][1] = -prices[i];
                    dp[i][0] = 0;
                } else {
                    //dp[i][1] = dp[i-1][1];
                    dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i]); 
                    if(i>=2) dp[i][1] = max(dp[i-1][1], dp[i-2][0] - prices[i]);
                    else dp[i][1] = max(dp[i-1][1], dp[i-1][0] - prices[i]);
                }
            }
            return dp[n-1][0];
        }
    };
    
  • 相关阅读:
    十一周总结
    第十周课程总结
    第九周课程总结&实验报告
    第八周课程总结&实验报告
    第七周&实验报告五
    第六周&Java实验报告四
    课程总结
    第十四周课程总结
    第十三周总结
    十二周课程总结
  • 原文地址:https://www.cnblogs.com/pk28/p/8635847.html
Copyright © 2011-2022 走看看