Skip to content

Commit 9ed96a7

Browse files
committed
Add solution #188
1 parent b2f32e2 commit 9ed96a7

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,7 @@
175175
174|[Dungeon Game](./0174-dungeon-game.js)|Hard|
176176
179|[Largest Number](./0179-largest-number.js)|Medium|
177177
187|[Repeated DNA Sequences](./0187-repeated-dna-sequences.js)|Medium|
178+
188|[Best Time to Buy and Sell Stock IV](./0188-best-time-to-buy-and-sell-stock-iv.js)|Hard|
178179
189|[Rotate Array](./0189-rotate-array.js)|Medium|
179180
190|[Reverse Bits](./0190-reverse-bits.js)|Easy|
180181
191|[Number of 1 Bits](./0191-number-of-1-bits.js)|Easy|
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* 188. Best Time to Buy and Sell Stock IV
3+
* https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/
4+
* Difficulty: Hard
5+
*
6+
* You are given an integer array prices where prices[i] is the price of a given stock on
7+
* the ith day, and an integer k.
8+
*
9+
* Find the maximum profit you can achieve. You may complete at most k transactions: i.e.
10+
* you may buy at most k times and sell at most k times.
11+
*
12+
* Note: You may not engage in multiple transactions simultaneously (i.e., you must sell
13+
* the stock before you buy again).
14+
*/
15+
16+
/**
17+
* @param {number} k
18+
* @param {number[]} prices
19+
* @return {number}
20+
*/
21+
var maxProfit = function(k, prices) {
22+
if (prices.length < 2 || k === 0) return 0;
23+
24+
if (k >= prices.length / 2) {
25+
let profit = 0;
26+
for (let i = 1; i < prices.length; i++) {
27+
profit += prices[i] > prices[i - 1] ? (prices[i] - prices[i - 1]) : 0;
28+
}
29+
return profit;
30+
}
31+
32+
const buy = new Array(k + 1).fill(-Infinity);
33+
const sell = new Array(k + 1).fill(0);
34+
for (let i = 0; i < prices.length; i++) {
35+
for (let j = k; j >= 1; j--) {
36+
sell[j] = Math.max(sell[j], buy[j] + prices[i]);
37+
buy[j] = Math.max(buy[j], sell[j - 1] - prices[i]);
38+
}
39+
}
40+
41+
return sell[k];
42+
};

0 commit comments

Comments
 (0)