Skip to content

Commit 71cf48e

Browse files
Merge pull request neetcode-gh#338 from shehanck/main
leetcode-309 solution in Java
2 parents 264dd81 + 4b22cd9 commit 71cf48e

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
public int maxProfit(int[] prices) {
3+
Map<String, Integer> cache = new HashMap<>();
4+
return dfs(prices, cache, 0, true);
5+
}
6+
7+
public int dfs(int[] prices, Map<String, Integer> cache, int index, boolean buying) {
8+
if (index >= prices.length) {
9+
return 0;
10+
}
11+
String key = index+"-"+buying;
12+
13+
if (cache.containsKey(key)) {
14+
return cache.get(key);
15+
}
16+
17+
int cooldown = dfs(prices, cache, index + 1, buying);
18+
int buyOsell = Integer.MIN_VALUE;
19+
20+
if (buying) {
21+
buyOsell = dfs(prices, cache, index + 1, !buying) - prices[index];
22+
} else {
23+
buyOsell = dfs(prices, cache, index + 2, !buying) + prices[index];
24+
}
25+
26+
cache.put(key, Math.max(buyOsell, cooldown));
27+
return cache.get(key);
28+
}
29+
}

0 commit comments

Comments
 (0)