LeetCode Best Time to Buy and Sell Stock with Cooldown

Posted Dylan_Java_NYC

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode Best Time to Buy and Sell Stock with Cooldown相关的知识,希望对你有一定的参考价值。

原题链接在这里: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:

 1 class Solution {
 2     public int maxProfit(int[] prices) {
 3         if(prices == null || prices.length < 2){
 4             return 0;
 5         }
 6         
 7         int b0 = -prices[0];
 8         int b1 = b0;
 9         int s2 = 0;
10         int s1 = 0;
11         int s0 = 0;
12         for(int i = 1; i<prices.length; i++){
13             b0 = Math.max(b1, s2-prices[i]);
14             s0 = Math.max(s1, b1+prices[i]);
15             
16             b1 = b0;
17             s2 = s1;
18             s1 = s0;
19         }
20         
21         return s0;
22     }
23 }

 

以上是关于LeetCode Best Time to Buy and Sell Stock with Cooldown的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 122. Best Time to Buy and Sell Stock II

Leetcode121. Best Time to Buy and Sell Stock

[LeetCode]Best Time to Buy and Sell Stock II

LeetCode OJ 121. Best Time to Buy and Sell Stock

LeetCode Best Time to Buy and Sell Stock

LeetCode - Best Time to Buy and Sell Stock