From c588dabdb41144855583d003dd7062a30abe411e Mon Sep 17 00:00:00 2001 From: Hyoga Murase Date: Tue, 18 Nov 2025 09:57:17 +0900 Subject: [PATCH] Create 20251118.ts --- .../20251118.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 src/leetcode/122_best-time-to-buy-and-sell-stock-ii/20251118.ts diff --git a/src/leetcode/122_best-time-to-buy-and-sell-stock-ii/20251118.ts b/src/leetcode/122_best-time-to-buy-and-sell-stock-ii/20251118.ts new file mode 100644 index 0000000..5c9c19a --- /dev/null +++ b/src/leetcode/122_best-time-to-buy-and-sell-stock-ii/20251118.ts @@ -0,0 +1,16 @@ +export function maxProfit(prices: number[]): number { + let maxProfit = 0; + let minPrice = prices[0]; + let totalProfit = 0 + + for (let i = 1; i < prices.length; i++) { + maxProfit = Math.max(maxProfit, prices[i] - minPrice); + minPrice = Math.min(minPrice, prices[i]); + + if (maxProfit > 0) { + totalProfit += maxProfit; + } + } + + return totalProfit; +};