Saturday 8 October 2022

Array - 122. Best Time to Buy and Sell Stock II

#===================================
# Tanzila Islam
# Email: tanzilamohita@gmail.com
# Language: Python 3
#===================================

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        profit = 0
        buy_p = 0
        cur = 0 # 0 = will buy, 1 = will sell
        
        for i in range(len(prices)-1):
            if cur == 0:
                if prices[i] < prices[i+1]:
                    buy_p = prices[i]
                    cur = 1
            else: 
                if prices[i] > prices[i+1]:
                    profit += prices[i] - buy_p
                    cur = 0
        
        if cur == 1:
            profit += prices[-1] - buy_p
            
        return profit

No comments:

Post a Comment