Best Time to Buy and Sell Stock - Python Solution

1. Introduction

"Best Time to Buy and Sell Stock" is a popular problem in the realm of financial computing and array manipulation. The challenge involves analyzing an array of stock prices and determining the optimal time to buy and sell a stock for the maximum profit. This problem is a classic example of using simple array traversal techniques for finding optimal solutions.


Given an array prices where prices[i] is the price of a given stock on the ith day, the goal is to maximize profit by choosing a single day to buy one stock and another day in the future to sell that stock. The task is to return the maximum profit that can be achieved from this transaction, or return 0 if no profit is possible.

2. Solution Steps

1. Initialize two variables: min_price to store the minimum price encountered so far and max_profit to store the maximum profit.

2. Traverse through the array of prices.

3. Update min_price with the minimum price found so far.

4. Calculate the profit for each day by subtracting the min_price from the current price.

5. Update max_profit if the calculated profit for the day is higher than the current max_profit.

6. Continue the process for each day in the price array.

7. Return the max_profit.

3. Code Program

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

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

    return max_profit

# Example Usage




1. Minimum Price Tracking: min_price keeps track of the lowest price seen so far in the array.

2. Profit Calculation: For each day, the potential profit is calculated as the difference between the current price and the min_price.

3. Maximum Profit Update: max_profit is updated if the profit for the current day is greater than the existing max_profit.

4. Iterative Approach: The array is iterated through once, updating min_price and max_profit as needed.

5. Result: The function returns the maximum profit possible from buying and selling a single stock. If no profit is possible, it returns 0.