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];
        }
    };
    
  • 相关阅读:
    mac 卸载 node并重新安装
    最小的Django应用
    Python如何实现文本转语音
    Python语言库pyttsx3
    大数据资料
    剑指offer(29)最小的K个数
    剑指offer(28)数组中出现次数超过一半的数
    剑指offer(27)字符串的排列
    剑指offer(26)二叉搜索树与双向链表
    JS、JAVA刷题和C刷题的一个很重要的区别
  • 原文地址:https://www.cnblogs.com/pk28/p/8635847.html
Copyright © 2011-2022 走看看