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; +};