Skip to content

Commit d68a7f8

Browse files
authored
Update 188-best-time-to-buy-and-sell-stock-iv.js
1 parent e26256e commit d68a7f8

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

188-best-time-to-buy-and-sell-stock-iv.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,36 @@ const maxProfit = function(k, prices) {
2525
return sell[k]
2626
}
2727

28+
// another
29+
30+
/**
31+
* @param {number} k
32+
* @param {number[]} prices
33+
* @return {number}
34+
*/
35+
const maxProfit = function(k, prices) {
36+
if(prices.length === 0) return 0
37+
38+
if(k > (prices.length/2)) {
39+
let profit = 0
40+
for(let i = 1; i < prices.length; i++) {
41+
if(prices[i] > prices[i-1]) profit += prices[i] - prices[i-1]
42+
}
43+
return profit
44+
} else {
45+
let dp = new Array(prices.length).fill(0)
46+
let length = prices.length
47+
for(let j = 0; j < k; j++) {
48+
let min = prices[0], max = 0
49+
for(let i = 0; i < length; i++) {
50+
min = Math.min(min, prices[i] - dp[i])
51+
max = Math.max(max, prices[i] - min)
52+
dp[i] = max
53+
}
54+
}
55+
return dp.pop()
56+
}
57+
}
2858

2959
// another
3060

0 commit comments

Comments
 (0)