#122

Best Time to Buy and Sell Stock II

Medium
ArrayDynamic ProgrammingGreedyGreedyArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution takes advantage of the fact that we can buy and sell on the same day. Instead of checking every pair, we simply add up all the profits from each upward price movement.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a variable to store total profit.
  2. 2Step 2: Iterate through the prices array from the first to the last day.
  3. 3Step 3: If the price on the next day is higher than the current day, add the difference to the total profit.
solution.py6 lines
1def maxProfit(prices):
2    total_profit = 0
3    for i in range(1, len(prices)):
4        if prices[i] > prices[i - 1]:
5            total_profit += prices[i] - prices[i - 1]
6    return total_profit

Complexity note: This complexity is linear because we only make a single pass through the prices array, checking adjacent days.

  • 1Buying low and selling high maximizes profit.
  • 2Multiple transactions can be beneficial in a fluctuating market.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.