Advertisement
i_love_rao_khushboo

Untitled

Sep 17th, 2022
1,006
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.89 KB | None | 0 0
  1. // Function to return the maximum product of a subarray of a given array
  2. ll max_prod_subarr(vll &v) {
  3.     int n = sz(v);
  4.     if(n == 0) return 0;
  5.    
  6.     // to store the final result
  7.     ll res = v[0];
  8.    
  9.     // max_ending_here = maximum product ending at the current index.
  10.     // min_ending_here = minimum product ending at the current index.
  11.     ll max_ending_here = v[0];
  12.     ll min_ending_here = v[0];
  13.    
  14.     for(int i = 1; i < n; i++) {
  15.         // update the maximum product ending at the current index
  16.         max_ending_here = max(v[i], v[i] * max_ending_here);
  17.        
  18.         // update the minimum product ending at the current index
  19.         min_ending_here = min(v[i], v[i] * min_ending_here);
  20.        
  21.         // swap max_ending_here & min_ending_here if required
  22.         if(max_ending_here < min_ending_here) {
  23.             swap(max_ending_here, min_ending_here);
  24.         }
  25.        
  26.         // update final result
  27.         res = max(res, max_ending_here);
  28.     }
  29.    
  30.     return res;
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement