AlgoMaster Logo

Best Time to Buy and Sell Stock

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

Intuition:

Using a brute force approach, we can try all possible combinations of buying and selling days and compute the profit for each combination. The maximum of these profits will be our answer.

Steps:

  1. Iterate through the list of prices with two nested loops.
  2. The outer loop will represent the buying day.
  3. The inner loop will represent the selling day.
  4. For each combination of buying and selling days, calculate the profit.
  5. Maintain a variable to keep track of the maximum profit observed.

Code:

2. One Pass Approach

Intuition:

Instead of trying all possible pairs of buy and sell days, we can iterate through the list of prices once while keeping track of the minimum price encountered so far. At each step, we calculate what the profit would be if we sold at the current price, and update the maximum profit correspondingly.

Approach:

Scan prices left to right while maintaining:

  • minPrice: the lowest price seen so far (best day to have bought before or on today).
  • maxProfit: the best profit achievable if we must sell on or after that minPrice day and on or before today.

At each day’s price p:

  1. Update minPrice = min(minPrice, p). This locks in the cheapest buy seen so far.
  2. Compute potential profit if we sell today: p - minPrice.
  3. Update maxProfit = max(maxProfit, p - minPrice).

Return maxProfit after the scan.

Code:

Example Walkthrough:

0
7
1
1
2
5
3
3
4
6
5
4
minPrice = MAX, maxProfit = 0
Step 1 / 7