Advertisement
RaFiN_

max product subarray

Dec 23rd, 2019
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.82 KB | None | 0 0
  1. int maxProduct(int A[], int n) {
  2.     // store the result that is the max we have found so far
  3.     int r = A[0];
  4.  
  5.     // imax/imin stores the max/min product of
  6.     // subarray that ends with the current number A[i]
  7.     for (int i = 1, imax = r, imin = r; i < n; i++) {
  8.         // multiplied by a negative makes big number smaller, small number bigger
  9.         // so we redefine the extremums by swapping them
  10.         if (A[i] < 0)
  11.             swap(imax, imin);
  12.  
  13.         // max/min product for the current number is either the current number itself
  14.         // or the max/min by the previous number times the current one
  15.         imax = max(A[i], imax * A[i]);
  16.         imin = min(A[i], imin * A[i]);
  17.  
  18.         // the newly computed max value is a candidate for our global result
  19.         r = max(r, imax);
  20.     }
  21.     return r;
  22. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement