From d2bbfa3ff422e1c22ec0282818b1696baae31963 Mon Sep 17 00:00:00 2001 From: kayac-chang Date: Wed, 25 Aug 2021 18:47:45 +0800 Subject: [PATCH] add hello solution --- 2021-08/2021-08-25 (day38)/Hello/solution.js | 23 ++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 2021-08/2021-08-25 (day38)/Hello/solution.js diff --git a/2021-08/2021-08-25 (day38)/Hello/solution.js b/2021-08/2021-08-25 (day38)/Hello/solution.js new file mode 100644 index 00000000..8cbceb21 --- /dev/null +++ b/2021-08/2021-08-25 (day38)/Hello/solution.js @@ -0,0 +1,23 @@ +const { max, min } = Math; + +/** + * @param {number[]} prices + * @return {number} + */ +function maxProfit(prices) { + let firstSell = 0; + let firstBuy = Infinity; + + let secondSell = 0; + let secondBuy = Infinity; + + for (const price of prices) { + firstBuy = min(firstBuy, price); + firstSell = max(firstSell, price - firstBuy); + + secondBuy = min(secondBuy, price - firstSell); + secondSell = max(secondSell, price - secondBuy); + } + + return secondSell; +}