Leetcode - Maximum Product Subarray
1331 ワード
Leetcode : Maximum Product Subarray
Description
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1
Input
Input
The presence of negative number and zero within the list can quickly change the values of maximum and minimum number. Hence, the program must compare every possible values - current, current * min, current * max
Solution (Python)
Description
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1
Input
[2,3,-2,4]
Output6
Example 2Input
[-2,0,-1]
Output0
ApproachThe presence of negative number and zero within the list can quickly change the values of maximum and minimum number. Hence, the program must compare every possible values - current, current * min, current * max
Solution (Python)
class Solution:
def maxProduct(self, nums: List[int]) -> int:
maxSub = nums[0]
minSub = nums[0]
result = nums[0]
for i in range(1, len(nums)):
curr = nums[i]
tempMax = max(curr, maxSub * curr, minSub * curr)
minSub = min(curr, maxSub * curr, minSub * curr)
maxSub = tempMax
result = max(maxSub, result)
return result
Reference
この問題について(Leetcode - Maximum Product Subarray), 我々は、より多くの情報をここで見つけました https://velog.io/@jiselectric/Leetcode-Maximum-Product-Subarrayテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol