Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Function to return the maximum product of a subarray of a given array
- ll max_prod_subarr(vll &v) {
- int n = sz(v);
- if(n == 0) return 0;
- // to store the final result
- ll res = v[0];
- // max_ending_here = maximum product ending at the current index.
- // min_ending_here = minimum product ending at the current index.
- ll max_ending_here = v[0];
- ll min_ending_here = v[0];
- for(int i = 1; i < n; i++) {
- // update the maximum product ending at the current index
- max_ending_here = max(v[i], v[i] * max_ending_here);
- // update the minimum product ending at the current index
- min_ending_here = min(v[i], v[i] * min_ending_here);
- // swap max_ending_here & min_ending_here if required
- if(max_ending_here < min_ending_here) {
- swap(max_ending_here, min_ending_here);
- }
- // update final result
- res = max(res, max_ending_here);
- }
- return res;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement