Best Time to Buy and Sell Stock Leetcode Python Solution

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.

Leetcode Python Solution

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        rolling_min = prices[0]
        max_profit = 0
        
        for i in range(0,len(prices)):
            curr_profit = prices[i]-rolling_min
            if curr_profit>max_profit:
                max_profit = curr_profit
            if prices[i]<rolling_min:
                rolling_min = prices[i]
                
        return max_profit

Elements of Programming Interviews in Python: The Insiders’ Guide

Unknown's avatar

Author: mathtuition88

Math and Education Blog

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.