From 1c6cef0582ce908a230594bdfdb4e75d5f4eca4a Mon Sep 17 00:00:00 2001 From: Young Kim Date: Mon, 9 Sep 2024 00:14:25 -0400 Subject: [PATCH] Best Time to Buy and Sell Stock solution --- best-time-to-buy-and-sell-stock/kimyoung.js | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 best-time-to-buy-and-sell-stock/kimyoung.js diff --git a/best-time-to-buy-and-sell-stock/kimyoung.js b/best-time-to-buy-and-sell-stock/kimyoung.js new file mode 100644 index 000000000..35518bcd1 --- /dev/null +++ b/best-time-to-buy-and-sell-stock/kimyoung.js @@ -0,0 +1,21 @@ +/** + * @param {number[]} prices + * @return {number} + */ +var maxProfit = function(prices) { + let left = 0, right = 1; + let max = 0; + + while(right < prices.length) { + if(prices[right] < prices[left]) { + left = right; + } else { + max = Math.max(max, prices[right] - prices[left]); + } + right++; + } + return max; +}; + +// time - O(n) iterate through prices once +// space - O(1)