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)
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)
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)
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