Advertisement
imashutosh51

Maximum product subarray

Oct 8th, 2022
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.50 KB | None | 0 0
  1. /*
  2. Logic:
  3. There is only two possiblity if there is not any zeros in array.
  4. either the subarray will be starting from left side or ending at right side.
  5. We will prove this by contracdiction,assume our answer is in between and left side
  6. multiplication is a and right side multiplication is b eg a ans b
  7. so there is 4 possibility for a and b
  8. a b
  9. + +
  10. + -
  11. - +
  12. - -
  13.  
  14. and two possibility for ans also positive and negative.
  15. if a and b is positive and ans is also positive then maxiumum product subarray will be whole array.
  16. if a and b is positive and ans is negative then  maxium product subaray wil be either a or b.
  17. similarly you can check for all possibility.
  18.  
  19. so one thing is proven that the maxiumum product subarray will be always start or end at corner so
  20. we can use one for loop which will start from the begining and multiply every element with it and update
  21. the answer and similary keep another loop from back side.
  22.  
  23. Now actual question comes,if 0 is there in loop still nothing changes,consider as a corner of the loop and if
  24. you get zero as multiplication make it as 1.
  25. */
  26.  
  27. class Solution {
  28. public:
  29.     int maxProduct(vector<int>& nums) {
  30.         int _max=INT_MIN,cur=1;
  31.         for(auto itr:nums){
  32.             cur*=itr;
  33.             _max=max(cur,_max);
  34.             if(cur==0) cur=1;
  35.         }
  36.        
  37.         cur=1;
  38.         for(int i=nums.size()-1;i>=0;i--){
  39.             cur*=nums[i];
  40.             _max=max(cur,_max);
  41.             if(cur==0) cur=1;
  42.         }
  43.         return _max;
  44.     }
  45. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement