Skip to content

Commit 272d113

Browse files
authored
Create 188-best-time-to-buy-and-sell-stock-iv.js
1 parent 6436218 commit 272d113

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* @param {number} k
3+
* @param {number[]} prices
4+
* @return {number}
5+
*/
6+
const maxProfit = function(k, prices) {
7+
if (!prices.length) return 0
8+
let len = prices.length,
9+
res = 0
10+
if (k >= ~~(len / 2)) {
11+
for (let i = 1; i < len; i++) {
12+
res += Math.max(prices[i] - prices[i - 1], 0)
13+
}
14+
return res
15+
}
16+
const buy = new Array(k + 1).fill(Number.MIN_SAFE_INTEGER)
17+
const sell = new Array(k + 1).fill(0)
18+
19+
for (let p of prices) {
20+
for (let i = 1; i <= k; i++) {
21+
buy[i] = Math.max(sell[i - 1] - p, buy[i])
22+
sell[i] = Math.max(buy[i] + p, sell[i])
23+
}
24+
}
25+
return sell[k]
26+
}

0 commit comments

Comments
 (0)