LeetCode 122 -Python 3 (Week 05 – 14)

Solution 1

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if len(prices) < 2: 
            return 0
        
        ans = 0
        for i in range(1, len(prices)):
            if prices[i] > prices[i-1]:
                ans += prices[i] - prices[i-1]
        return ans
            

Time complexity is O(n). Space complexity is O(1).

Leave a comment

Design a site like this with WordPress.com
Get started