LeetCode Best Time to Buy and Sell Stock with Cooldown

时间:2022-08-02 17:52:06

原题链接在这里:https://leetcode.com/problems/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]

题解:

Let buy[i] denotes maximum profit till index i, series of transactions ending with buy.

Let sell[i] denotes maimum profit till index i, series of transactions ending with sell.

There is a cooldown before buy again. buy[i] could happend after sell[i-2], not sell[i-1].

Thus, buy[i] = Math.max(buy[i-1], sell[i-2]-prices[i]).

If wanna sell a stock, must buy stock before. Thus sell[i] is calculated with buy[i-1].

sell[i] = Math.max(sell[i-1], buy[i-1]+prices[i]).

只用到了i-1, i-2两个之前的量,所以可以使用常量来代替数组.

b0 as buy[i], b1 as buy[i-1].

s0 as sell[i], s1 as sell[i-1], s2 as sell[i-2].

Time Complexity: O(n). n = prices.length.

Space: O(1).

AC Java:

 class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length < 2){
return 0;
} int b0 = -prices[0];
int b1 = b0;
int s2 = 0;
int s1 = 0;
int s0 = 0;
for(int i = 1; i<prices.length; i++){
b0 = Math.max(b1, s2-prices[i]);
s0 = Math.max(s1, b1+prices[i]); b1 = b0;
s2 = s1;
s1 = s0;
} return s0;
}
}