Skip to main content

Best Time to Buy and Sell Stock


What is the maximum profit that can be made by buying and selling a single stock within a given array of daily stock prices?

Example 1


all//Best Time to Buy and Sell

# Python Program for Best Time to Buy and Sell Stock
# Problem Statement:
# Say you have an array for which the ith element is the price of a given stock on day i.
# If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock),
# design an algorithm to find the maximum profit.

# Note that you cannot sell a stock before you buy one.

# Input: [7,1,5,3,6,4]
# Output: 5
# Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
# Not 7-1 = 6, as selling price needs to be larger than buying price.

# Algorithm:
# 1. Create a variable called max_profit and set it to 0. This will keep track of the maximum profit.
# 2. Iterate through the list of stock prices.
# 3. For each iteration, calculate the difference between the current price and the minimum price seen so far.
# 4. Update the max_profit variable if the difference is greater than the max_profit.
# 5. Update the minimum price seen so far.
# 6. Return the max_profit.

def maxProfit(prices):
max_profit = 0
min_price = float('inf')

for price in prices:
min_price = min(min_price, price)
profit = price - min_price
max_profit = max(max_profit, profit)
return max_profit

# Driver function
prices = [7, 1, 5, 3, 6, 4]
print("Maximum Profit:", maxProfit(prices))