-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaxProduct.cpp
More file actions
42 lines (30 loc) · 970 Bytes
/
Copy pathmaxProduct.cpp
File metadata and controls
42 lines (30 loc) · 970 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/*
Given an array Arr that contains N integers (may be positive, negative or zero).
Find the product of the maximum product subarray.
Input:
N = 5
Arr[] = {6, -3, -10, 0, 2}
Output: 180
Explanation: Subarray with maximum product
is 6, -3, -10 which gives product as 180.
*/
class Solution{
public:
// Function to find maximum product subarray
long long maxProduct(int *arr, int n)
{
long long minValue = arr[0];
long long maxValue = arr[0];
long long maxProduct = arr[0];
for(int i=1;i<n;i++)
{
if(arr[i]<0) swap(minValue,maxValue);
if(arr[i]*maxValue>arr[i]) maxValue = arr[i]*maxValue;
else maxValue = arr[i];
if(arr[i]*minValue<arr[i]) minValue = arr[i]*minValue;
else minValue = arr[i];
maxProduct = max(maxProduct, maxValue);
}
return maxProduct;
}
};