Skip to content

Commit

Permalink
Merge pull request neetcode-gh#338 from shehanck/main
Browse files Browse the repository at this point in the history
leetcode-309 solution in Java
  • Loading branch information
SharmaTushar1 authored Jun 28, 2022
2 parents 264dd81 + 4b22cd9 commit 71cf48e
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions java/309-Best-Time-To-Buy-and-Sell-Stock-With-Cooldown.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
class Solution {
public int maxProfit(int[] prices) {
Map<String, Integer> cache = new HashMap<>();
return dfs(prices, cache, 0, true);
}

public int dfs(int[] prices, Map<String, Integer> cache, int index, boolean buying) {
if (index >= prices.length) {
return 0;
}
String key = index+"-"+buying;

if (cache.containsKey(key)) {
return cache.get(key);
}

int cooldown = dfs(prices, cache, index + 1, buying);
int buyOsell = Integer.MIN_VALUE;

if (buying) {
buyOsell = dfs(prices, cache, index + 1, !buying) - prices[index];
} else {
buyOsell = dfs(prices, cache, index + 2, !buying) + prices[index];
}

cache.put(key, Math.max(buyOsell, cooldown));
return cache.get(key);
}
}

0 comments on commit 71cf48e

Please sign in to comment.