-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBestTimeToBuySellStockCoolDown.java
More file actions
39 lines (34 loc) · 1.36 KB
/
BestTimeToBuySellStockCoolDown.java
File metadata and controls
39 lines (34 loc) · 1.36 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
/*
You are given an array prices where prices[i] is the price of a given stock on the ith day.
Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:
After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day)
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Example 1:
Input: prices = [1,2,3,0,2]
Output: 3
Explanation: transactions = [buy, sell, cooldown, buy, sell]
*/
public class Solution {
private Map<String, Integer> dp = new HashMap<>();
public int maxProfit(int[] prices) {
return dfs(0, true, prices);
}
private int dfs(int i, boolean buying, int[] prices) {
if (i >= prices.length) {
return 0;
}
String key = i + "-" + buying;
if (dp.containsKey(key)) {
return dp.get(key);
}
int cooldown = dfs(i + 1, buying, prices);
if (buying) {
int buy = dfs(i + 1, false, prices) - prices[i];
dp.put(key, Math.max(buy, cooldown));
} else {
int sell = dfs(i + 2, true, prices) + prices[i];
dp.put(key, Math.max(sell, cooldown));
}
return dp.get(key);
}
}