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 resultresall be the first number of the array. -
Start from the second number, let say when we are on the
ith number, if theith number is positive, then we use the current maximum number multiple by it in order to get the maximum result. If theith number is negative, then we use the current minimum number multiple by it to get the maximum result. Therefore, no matter theith 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 gettingcurMaxandcurMin, we will update the resultres = max(res, curMax).
Solution
1 | |