Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Logic:
- There is only two possiblity if there is not any zeros in array.
- either the subarray will be starting from left side or ending at right side.
- We will prove this by contracdiction,assume our answer is in between and left side
- multiplication is a and right side multiplication is b eg a ans b
- so there is 4 possibility for a and b
- a b
- + +
- + -
- - +
- - -
- and two possibility for ans also positive and negative.
- if a and b is positive and ans is also positive then maxiumum product subarray will be whole array.
- if a and b is positive and ans is negative then maxium product subaray wil be either a or b.
- similarly you can check for all possibility.
- so one thing is proven that the maxiumum product subarray will be always start or end at corner so
- we can use one for loop which will start from the begining and multiply every element with it and update
- the answer and similary keep another loop from back side.
- Now actual question comes,if 0 is there in loop still nothing changes,consider as a corner of the loop and if
- you get zero as multiplication make it as 1.
- */
- class Solution {
- public:
- int maxProduct(vector<int>& nums) {
- int _max=INT_MIN,cur=1;
- for(auto itr:nums){
- cur*=itr;
- _max=max(cur,_max);
- if(cur==0) cur=1;
- }
- cur=1;
- for(int i=nums.size()-1;i>=0;i--){
- cur*=nums[i];
- _max=max(cur,_max);
- if(cur==0) cur=1;
- }
- return _max;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement