Leet Code

#2 Best Time to Buy and Sell Stock

brian | Published: March 14, 2024, 11:43 a.m. | Updated: July 9, 2025, 9:20 p.m.

Profile Picture
'''
You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

 

Example 1:

Input: prices = [7,1,5,3,6,4]
Output: 5
'''

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """

        left_pointer = 0
        right_pointer = 1
        max_profit = 0

        while right_pointer < len(prices):
             #if the right pointer value is > than left, only then we check, because if its not greater
             #then we already know there wont be profit so theres no point in doing the math
            
            if prices[right_pointer] > prices[left_pointer]:
               
                profit = prices[right_pointer] - prices[left_pointer]
                print(f'left pointer: {left_pointer} right pointer: {right_pointer} profit: {profit}')
                max_profit = max(max_profit, profit)
            else:
                left_pointer = right_pointer

            right_pointer+=1
        return max_profit

     

prices = [5, 7, 3, 9, 6, 1]
s = Solution()

print(s.maxProfit(prices))
        
#answer: 6



------output------
left pointer: 0 right pointer: 1 profit: 2
left pointer: 2 right pointer: 3 profit: 6
left pointer: 2 right pointer: 4 profit: 3
6