LeetCode-Best Time to Buy and Sell Stock with Cooldown

LiBlog發表於2016-07-22

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]

Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.

 

Analysis:

Always consider two situations: hold[i]: we have stock on hand at ith day; unhold[i]: we do not have stock on hand at ith day.

 

Solution:

 1 public class Solution {
 2     public int maxProfit(int[] prices) {
 3         if (prices.length<2) return 0;
 4 
 5         int[] hold = new int[prices.length];
 6         int[] unhold = new int[prices.length];
 7 
 8         hold[0] = -prices[0];
 9         unhold[0] = 0;
10         hold[1] = Math.max(hold[0],-prices[1]);
11         unhold[1] = Math.max(0,hold[0]+prices[1]);
12 
13         for (int i=2;i<prices.length;i++){
14             hold[i] = Math.max(hold[i-1], unhold[i-2]-prices[i]);
15             unhold[i] = Math.max(unhold[i-1],hold[i-1]+prices[i]);
16         }
17 
18         return Math.max(hold[prices.length-1],unhold[prices.length-1]);
19     }
20 }

 

相關文章