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

    xiaoxiao2022-06-30  58

    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]

    有两个状态,“持有”和“卖出”(或“非持有”)。has[i]和hasnot[i]分别表示第i+1天结束后所剩下的钱的最大值,状态方程为:

    has[i] = max( has[i-1], hasnot[i-2] - prices[i] )       hasnot[i] = max( has[i-1] + prices[i], hasnot[i-1])

    由于状态方程里出现了 i-2,于是初值为:

    has[0] = -prices[0];  hasnot[0] = 0;  has[1] = max( -prices[0], 0 ) = 0;  hasnot[1] = max( prices[1] - prices[0], 0 )

    class Solution { public: int maxProfit(vector<int>& prices) { if (prices.size() <= 1) return 0; int len = prices.size(); int* has = new int[len]; //has[i]表示第i天是“持有”状态,i从0开始 int* hasnot = new int[len]; //hasnot[i]表示第i天是“卖出"或“非持有”状态 has[0] = -prices[0], has[1] = max(-prices[0], -prices[1]); hasnot[0] = 0, hasnot[1] = max(prices[1] - prices[0], 0); for (int i = 2; i < len; i++) { has[i] = max(has[i - 1], hasnot[i - 2] - prices[i]); hasnot[i] = max(has[i - 1] + prices[i], hasnot[i - 1]); } return max(has[len - 1], hasnot[len - 1]); } };

    转载请注明原文地址: https://ju.6miu.com/read-1125833.html

    最新回复(0)