Advertisement
Guest User

Untitled

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