6/26/2020

[LeetCode] 122. Best Time to Buy and Sell Stock II

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

Should collect every possible profit

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

One liner solution:


class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        return sum(b - a for a, b in zip(prices, prices[1:]) if b > a)

Edited on 11/09/2021. Add the one liner solution.

No comments:

Post a Comment