[Geeks for Geeks] Maximum Product Subarray

Maximum Product Subarray

Given an array Arr[] that contains N integers (may be positive, negative or zero). Find the product of the maximum product subarray.

  • Time : O(n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
// Function to find maximum product subarray
long long maxProduct(vector<int> arr, int n) {
long long res = LLONG_MIN, first = LLONG_MIN, product = 1;
for(auto& a : arr) {
if(!a) {
if(abs(product) > abs(first)) {
res = max(res, product / first);
}
res = max(res, 0ll);
first = LLONG_MIN, product = 1;
} else {
product *= a;
if(first == LLONG_MIN and product < 0) first = product;
res = max(res, product);
}
}
if(abs(product) > abs(first)) {
res = max(res, product / first);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/20/PS/GeeksforGeeks/maximum-product-subarray/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.