Best Time to Buy and Sell Stock in Python

The Best Time to Buy and Sell Stock problem asks us to find the maximum profit from buying and selling a stock once. Given an array where each element represents the stock price on a specific day, we need to determine the optimal buy and sell days to maximize profit.

For example, if prices = [7, 1, 5, 3, 6, 4], the maximum profit is 5 (buy at price 1 on day 2, sell at price 6 on day 5).

Algorithm Approach

We can solve this using two auxiliary arrays:

  • leftMin: stores the minimum price from the start up to each day
  • rightMax: stores the maximum price from each day to the end

The maximum profit is the largest difference between rightMax[i+1] and leftMin[i] for any valid day i.

Step-by-Step Solution

class Solution:
    def maxProfit(self, prices):
        """
        Find maximum profit from buying and selling stock once
        :type prices: List[int]
        :rtype: int
        """
        if not prices or len(prices) < 2:
            return 0
        
        n = len(prices)
        leftMin = [0] * n
        rightMax = [0] * n
        
        # Fill leftMin array - minimum price from start to each day
        leftMin[0] = prices[0]
        for i in range(1, n):
            leftMin[i] = min(leftMin[i-1], prices[i])
        
        # Fill rightMax array - maximum price from each day to end
        rightMax[n-1] = prices[n-1]
        for i in range(n-2, -1, -1):
            rightMax[i] = max(rightMax[i+1], prices[i])
        
        # Find maximum profit
        max_profit = 0
        for i in range(n-1):
            profit = rightMax[i+1] - leftMin[i]
            max_profit = max(max_profit, profit)
        
        return max_profit

# Test the solution
solution = Solution()
prices = [7, 2, 5, 8, 6, 3, 1, 4, 5, 4, 7]
result = solution.maxProfit(prices)
print(f"Maximum profit: {result}")
Maximum profit: 6

How It Works

Let's trace through the algorithm with prices = [7, 2, 5, 8, 6, 3, 1, 4, 5, 4, 7]:

prices = [7, 2, 5, 8, 6, 3, 1, 4, 5, 4, 7]

# leftMin array - minimum price up to each day
leftMin = [7, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1]

# rightMax array - maximum price from each day onwards
rightMax = [8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7]

# Calculate profit for each possible buy day
for i in range(len(prices)-1):
    profit = rightMax[i+1] - leftMin[i]
    print(f"Day {i}: buy at {leftMin[i]}, sell at {rightMax[i+1]}, profit = {profit}")
Day 0: buy at 7, sell at 8, profit = 1
Day 1: buy at 2, sell at 8, profit = 6
Day 2: buy at 2, sell at 8, profit = 6
Day 3: buy at 2, sell at 8, profit = 6
Day 4: buy at 2, sell at 7, profit = 5
Day 5: buy at 2, sell at 7, profit = 5
Day 6: buy at 1, sell at 7, profit = 6
Day 7: buy at 1, sell at 7, profit = 6
Day 8: buy at 1, sell at 7, profit = 6
Day 9: buy at 1, sell at 7, profit = 6

Optimized Single Pass Solution

We can solve this more efficiently using a single pass approach:

def maxProfitOptimized(prices):
    """
    Optimized solution using single pass
    """
    if not prices or len(prices) < 2:
        return 0
    
    min_price = prices[0]
    max_profit = 0
    
    for i in range(1, len(prices)):
        # Update minimum price seen so far
        min_price = min(min_price, prices[i])
        
        # Calculate profit if we sell today
        profit = prices[i] - min_price
        
        # Update maximum profit
        max_profit = max(max_profit, profit)
    
    return max_profit

# Test both approaches
prices = [7, 1, 5, 3, 6, 4]
print(f"Two-pass solution: {Solution().maxProfit(prices)}")
print(f"Single-pass solution: {maxProfitOptimized(prices)}")
Two-pass solution: 5
Single-pass solution: 5

Comparison

Approach Time Complexity Space Complexity Passes
Two Arrays O(n) O(n) 3
Single Pass O(n) O(1) 1

Conclusion

Both approaches solve the stock trading problem effectively. The two-array method is easier to understand, while the single-pass approach is more space-efficient with O(1) memory usage.

Updated on: 2026-03-25T07:12:07+05:30

644 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements