iT邦幫忙

2022 iThome 鐵人賽

0
自我挑戰組

LeetCode Top 100 Liked系列 第 35

[Day 35] 122. Best Time to Buy and Sell Stock II (Medium)

  • 分享至 

  • xImage
  •  

122. Best Time to Buy and Sell Stock II

Solution 1: DP

Time Complexity: O(N)
Space Complexity: O(1)

Solution 2: Geedy

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

Time Complexity: O(N)
Space Complexity: O(1)

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/discuss/803206/PythonJSJavaGoC%2B%2B-O(n)-by-DP-Greedy-%2B-Visualization


上一篇
[Day 34] Find the Duplicate Number (Medium)
下一篇
[Day 36] Intersection of Two Linked Lists (Easy)
系列文
LeetCode Top 100 Liked77
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言