-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBestTimeToBuyAndSellStockWithCooldown.java
More file actions
55 lines (46 loc) · 1.68 KB
/
BestTimeToBuyAndSellStockWithCooldown.java
File metadata and controls
55 lines (46 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package dynamic_programming;
/**
* Description: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown
* Difficulty: Medium
*/
public class BestTimeToBuyAndSellStockWithCooldown {
/**
* Time complexity: O(n)
* Space complexity: O(1)
*/
public int maxProfitViaStateMachine(int[] prices) {
int rested = 0;
int sold = 0;
int bought = -prices[0];
for (int i = 1; i < prices.length; i++) {
int prevRested = rested;
int prevSold = sold;
int prevBought = bought;
// can get to RESTED from RESTED or SOLD states by resting
rested = Math.max(prevRested, prevSold);
// can get to SOLD from BOUGHT by selling
sold = prevBought + prices[i];
// can get to BOUGHT from BOUGHT by resting or RESTED by buying
bought = Math.max(prevBought, prevRested - prices[i]);
}
return Math.max(rested, sold);
}
/**
* Time complexity: O(n^2)
* Space complexity: O(n)
*/
public int maxProfitViaDP(int[] prices) {
int[] dp = new int[prices.length];
dp[0] = 0;
for (int current = 1; current < prices.length; current++) {
for (int prev = current; prev >= 0; prev--) {
int buyPrev = prev > 1 ? dp[prev - 1] : 0;
int prevPossibleProfit = prev > 2 ? dp[prev - 2] : 0;
int sellNow = Math.max(prices[current] - prices[prev], 0);
int maxProfit = Math.max(buyPrev, prevPossibleProfit + sellNow);
dp[current] = Math.max(dp[current], maxProfit);
}
}
return dp[dp.length - 1];
}
}