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.
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: 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; } };
|