Question 121 Best Time to Buy and Sell Stock

The description of the question is given in the following link:

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

My code:

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if len(prices) == 0:
            return 0
        else:
            Maximum = 0
            Buy = prices[0]
            Index = 1
            i= 1
            while(i<len(prices)):
                Sell = prices[i]
                profit = Sell-Buy
                if profit< 0:
                    Buy = Sell
                Maximum = max(profit, Maximum)
                i +=1
            return Maximum

Explanation:

This code is straightforward: We start from first element as buy in . Whenever we have a negative profit, it means that we have a lower price later, hence for any profit we have later, buy in with the lower price will definitely give the larger profit, that’s why we substitute the buy with sell here. Then for each time we compare the profit we have with the previous profit, which gives the maximum.

 

 

 

 

 

Leave a comment