iT邦幫忙

2022 iThome 鐵人賽

0
自我挑戰組

LeetCode Top 100 Liked系列 第 47

[Day 47] Maximum Product Subarray (Medium)

  • 分享至 

  • xImage
  •  

152. Maximum Product Subarray

Solution 1: DP

class Solution:
    def maxProduct(self, nums: List[int]) -> int:
        n = len(nums)
        if n < 1:
            return 0
        if n == 1:
            return nums[0]
        
        maxProductSumToI = [nums[0]] + (n-1)*[0]
        minProductSumToI = [nums[0]] + (n-1)*[0]
        ans = nums[0]
        for idx in range(1, n):            
            currValTimesPrevMax = nums[idx] * maxProductSumToI[idx - 1]
            currValTimesPrevMin = nums[idx] * minProductSumToI[idx - 1]
            maxProductSumToI[idx] = max(currValTimesPrevMax, currValTimesPrevMin, nums[idx])
            minProductSumToI[idx] = min(currValTimesPrevMax, currValTimesPrevMin, nums[idx])
            ans = max(ans, maxProductSumToI[idx])
        return ans

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

Solution 2: Rolling DP

class Solution:
    def maxProduct(self, nums: List[int]) -> int:
        n = len(nums)
        if n < 1:
            return 0
        if n == 1:
            return nums[0]

        maxProductSumToI = nums[0]
        minProductSumToI = nums[0]
        ans = nums[0]
        for idx in range(1, n):            
            currValTimesPrevMax = nums[idx] * maxProductSumToI
            currValTimesPrevMin = nums[idx] * minProductSumToI
            maxProductSumToI = max(currValTimesPrevMax, currValTimesPrevMin, nums[idx])
            minProductSumToI = min(currValTimesPrevMax, currValTimesPrevMin, nums[idx])
            ans = max(ans, maxProductSumToI)
        return ans

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

Solution 3: Variant of Kadane's algorithm

class Solution:
    def maxProduct(self, nums: List[int]) -> int:
        n = len(nums)
        if n < 1:
            return 0
        if n == 1:
            return nums[0]
        
        numsRev = nums[::-1]
        for idx in range(1, n):
            nums[idx] = (nums[idx] * nums[idx - 1]) or nums[idx]
            numsRev[idx] = (numsRev[idx] * numsRev[idx - 1]) or numsRev[idx]
        return max(nums + numsRev)

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

Reference

https://leetcode.com/problems/maximum-product-subarray/discuss/48261/Share-my-DP-code-that-got-AC
https://leetcode.com/problems/maximum-product-subarray/discuss/48230/Possibly-simplest-solution-with-O(n)-time-complexity
https://leetcode.com/problems/maximum-product-subarray/discuss/183483/JavaC%2B%2BPython-it-can-be-more-simple


上一篇
[Day 46] Zigzag Conversion (Medium)
下一篇
[Day 48] Kth Largest Element in an Array (Medium)
系列文
LeetCode Top 100 Liked77
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言