Algorithm Steps
- Given an array
prices
whereprices[i]
represents the price of a stock on theith
day. - Initialize
min_price
to a very large number andmax_profit
to 0. - Traverse through the array:
- → If
prices[i]
is less thanmin_price
, updatemin_price
. - → Else, calculate the profit by
prices[i] - min_price
and updatemax_profit
if it is greater. - 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))