PROBLEM DESCRIPTION
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).
SOLUTION
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
class Solution {
public int maxProfit(int[] prices) {
return profitHelper(prices, true, 0, new HashMap<>());
}
public int profitHelper(int[] prices, boolean buying, int idx, Map<String, Integer> map){
if(idx >= prices.length) return 0;
if(!map.containsKey(idx+":"+buying)){
if(buying){
int amount = profitHelper(prices, !buying, idx+1, map) - prices[idx];
int cooldown = profitHelper(prices, buying, idx+1, map);
int max = Math.max(amount, cooldown);
map.put(idx+":"+buying, max);
}else{
int amount = profitHelper(prices, !buying, idx+2, map) + prices[idx];
int cooldown = profitHelper(prices, buying, idx+1, map);
int max = Math.max(amount, cooldown);
map.put(idx+":"+buying, max);
}
}
return map.get(idx+":"+buying);
}
}