Stock Buy and Sell - Optimal Approach

Stock Buy and Sell - Optimal Approach

Visualization

Algorithm Steps

  1. Given an array prices where prices[i] represents the price of a stock on the ith day.
  2. Initialize min_price to a very large number and max_profit to 0.
  3. Traverse through the array:
  4. → If prices[i] is less than min_price, update min_price.
  5. → Else, calculate the profit by prices[i] - min_price and update max_profit if it is greater.
  6. After the loop, return max_profit.

Maximum Profit from Stock Buy and Sell using Optimal Approach Code

Python
JavaScript
Java
C++
C
def max_profit(prices):
    min_price = float('inf')
    max_profit = 0
    for price in prices:
        if price < min_price:
            min_price = price
        elif price - min_price > max_profit:
            max_profit = price - min_price
    return max_profit

# Sample Input
prices = [7, 1, 5, 3, 6, 4]
print("Max Profit:", max_profit(prices))