-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaximumProductSubarray.cpp
More file actions
34 lines (32 loc) · 888 Bytes
/
maximumProductSubarray.cpp
File metadata and controls
34 lines (32 loc) · 888 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
#include <bits/stdc++.h>
using namespace std;
#define ll long long
ll maxproductSub(int* arr, int n){
ll max_product = 0;
ll max_end_here = 1, min_end_here = 1;
for(int i = 0; i < n; i++){
if(arr[i] > 0){
max_end_here *= arr[i];
min_end_here = min(min_end_here * arr[i], 1);
}else if(arr[i] < 0){
int temp = max_end_here;
max_end_here = max(min_end_here * arr[i], 1);
min_end_here = temp * arr[i];
}
}else{
min_end_here = 1;
max_end_here = 1;
}
max_product = max(max_product, max_end_here);
}
return max_product; //6 -3 5 -10 0 2
}
int main(){
int n;
cin >> n;
int* arr = new int[n];
for(int i = 0; i < n; i++){
cin > >arr[i];
}
cout << maxProductSub(arr, n)<<endl;
}