loading

Best Time to Buy and Sell Stock II — Step-by-Step Visualization

mediumLeetCode #122ArrayGreedy

You are given an integer array prices where prices[i] is the price of a given stock on the ith day. On each day, you may decide to buy and/or sell the stock. Return the maximum profit you can achieve.

Algorithm Pattern

Greedy

Key Idea

Collect every upward move — any rising segment contributes to profit.

Step-by-Step Approach

  1. For each consecutive pair
  2. If price rises, add the difference to profit

Related Problems