Problem
Given an integer array nums
, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
1 |
|
Example 2:
1 |
|
Explanation
-
We can solve this problem in one loop. In each iteration, we need to keep track of the maximum result ending here
curMax
, and minimum result ending herecurMin
. We can initializecurMax
,curMin
, and resultres
all be the first number of the array. -
Start from the second number, let say when we are on the
i
th number, if thei
th number is positive, then we use the current maximum number multiple by it in order to get the maximum result. If thei
th number is negative, then we use the current minimum number multiple by it to get the maximum result. Therefore, no matter thei
th number is positive or negative, we can get the maximum result bycurMax = max(nums[i], curMax * nums[i], curMin * nums[i])
. Similarlly, we can get the minimum result bycurMin = min(nums[i], curMax * nums[i], curMin * nums[i])
. After gettingcurMax
andcurMin
, we will update the resultres = max(res, curMax)
.
Solution
1 |
|