|
| 1 | +/* |
| 2 | +Maximum Product Subarray |
| 3 | +======================== |
| 4 | +
|
| 5 | +Given an array Arr that contains N integers (may be positive, negative or zero). Find the product of the maximum product subarray. |
| 6 | +
|
| 7 | +Example 1: |
| 8 | +Input: |
| 9 | +N = 5 |
| 10 | +Arr[] = {6, -3, -10, 0, 2} |
| 11 | +Output: 180 |
| 12 | +Explanation: Subarray with maximum product |
| 13 | +is 6, -3, -10 which gives product as 180. |
| 14 | +
|
| 15 | +Example 2: |
| 16 | +Input: |
| 17 | +N = 6 |
| 18 | +Arr[] = {2, 3, 4, 5, -1, 0} |
| 19 | +Output: 120 |
| 20 | +Explanation: Subarray with maximum product |
| 21 | +is 2, 3, 4, 5 which gives product as 120. |
| 22 | +Your Task: |
| 23 | +You don't need to read input or print anything. Your task is to complete the function maxProduct() which takes the array of integers arr and n as parameters and returns an integer denoting the answer. |
| 24 | +Note: Use 64-bit integer data type to avoid overflow. |
| 25 | +
|
| 26 | +Expected Time Complexity: O(N) |
| 27 | +Expected Auxiliary Space: O(1) |
| 28 | +
|
| 29 | +Constraints: |
| 30 | +1 <= N <= 500 |
| 31 | +-102 <= Arri <= 102 |
| 32 | +*/ |
| 33 | + |
| 34 | +long long maxProduct(int *nums, int n) |
| 35 | +{ |
| 36 | + long long min_here = nums[0], max_here = nums[0], ans = nums[0]; |
| 37 | + |
| 38 | + for (int i = 1; i < n; ++i) |
| 39 | + { |
| 40 | + if (nums[i] < 0) |
| 41 | + swap(max_here, min_here); |
| 42 | + |
| 43 | + max_here = max((long long)nums[i], max_here * nums[i]); |
| 44 | + min_here = min((long long)nums[i], min_here * nums[i]); |
| 45 | + |
| 46 | + ans = max(ans, max_here); |
| 47 | + } |
| 48 | + |
| 49 | + return ans; |
| 50 | +} |
0 commit comments