LeetCode solutions

122. Best Time to Buy and Sell Stock II

My accepted JavaScript solution to LeetCode problem 122, Best Time to Buy and Sell Stock II, running in 1ms.

  • Difficulty: Medium
  • JavaScript
  • Runtime 1ms
  • Memory 54.6MB

Read the problem on LeetCode View on GitHub

JavaScript

Accepted on LeetCode — runtime 1ms, memory 54.6MB, accepted 2025-12-24.

javascript
/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    // Greedy: capture every upward slope
    let profit = 0;
    
    for (let i = 1; i < prices.length; i++) {
        if (prices[i] > prices[i - 1]) {
            profit += prices[i] - prices[i - 1];
        }
    }
    
    return profit;
};

Source