Skip to content

Commit

Permalink
Create 309-Best-Time-To-Buy-And-Sell-Stock-With-Cooldown.js
Browse files Browse the repository at this point in the history
  • Loading branch information
Ahmad-A0 authored Aug 31, 2022
1 parent 6e16474 commit 77d23a1
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions javascript/309-Best-Time-To-Buy-And-Sell-Stock-With-Cooldown.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
let dp = {} // key=[i, buying] val=max_profit

const dfs = (i, buying) => {
if (i >= prices.length) return 0
if (dp[[i, buying]]) return dp[[i, buying]]

const cooldown = dfs(i + 1, buying)
if (buying) {
const buy = dfs(i + 1, !buying) - prices[i]
dp[[i, buying]] = Math.max(buy, cooldown)
}
else {
sell = dfs(i + 2, !buying) + prices[i]
dp[[i, buying]] = Math.max(sell, cooldown)
}
return dp[[i, buying]]
}

return dfs(0, true)
};

0 comments on commit 77d23a1

Please sign in to comment.