CODE/Algorithms & Data Structures

[Coderust] Stock Buy Sell to Maximize Profit

BoriTea 2022. 2. 27. 11:16

 

 

Problem

 

 


 

Solution

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        low = -1
        profit = 0
        
        for price in prices:
            if price < low:
                low = price
                continue
            
            if price - low > profit:
                if low < 0:
                    low = price
                else:
                    profit = price - low
        
        
        return profit

 

Time Complexity

O(N)

 

 

Space Complexity

O(1)