We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 6436218 commit 272d113Copy full SHA for 272d113
188-best-time-to-buy-and-sell-stock-iv.js
@@ -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