[InterviewBit] Max Product Subarray

Max Product Subarray

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
int Solution::maxProduct(const vector<int> &A) {
int res = INT_MIN;
int all = 1, n = A.size(), st = 0;
for(int i = 0; i <= n; i++) {
if(i == n or A[i] == 0) {
if(A[i] == 0) res = max(res, 0);
if(st == i) {}
else if(all > 0) res = max(res, all);
else {
int left = 1, right = 1;
for(int j = st; left > 0; j++) left *= A[j];
for(int j = i - 1; right > 0; j--) right *= A[j];
if(left == all) res = max(res, all);
else res = max(res, all / left);
if(right == all) res = max(res,all);
else res = max(res, all / right);
}
all = 1;
st = i + 1;
} else all *= A[i];
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/10/PS/interviewbit/max-product-subarray/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.