Skip to content

Commit cb07316

Browse files
authored
Create 123-best-time-to-buy-and-sell-stock-iii.js
1 parent a0871e7 commit cb07316

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed
+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
/**
2+
* @param {number[]} prices
3+
* @return {number}
4+
*/
5+
const maxProfit = function(prices) {
6+
let maxProfit1 = 0
7+
let maxProfit2 = 0
8+
let lowestBuyPrice1 = Number.MAX_VALUE
9+
let lowestBuyPrice2 = Number.MAX_VALUE
10+
11+
for (let p of prices) {
12+
maxProfit2 = Math.max(maxProfit2, p - lowestBuyPrice2)
13+
lowestBuyPrice2 = Math.min(lowestBuyPrice2, p - maxProfit1)
14+
maxProfit1 = Math.max(maxProfit1, p - lowestBuyPrice1)
15+
lowestBuyPrice1 = Math.min(lowestBuyPrice1, p)
16+
}
17+
return maxProfit2
18+
}

0 commit comments

Comments
 (0)