nikunjsoni

152

Dec 3rd, 2021
732
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Solution {
  2. public:
  3.     int maxProduct(vector<int>& nums) {
  4.         int ans=-1e9,n=nums.size(),l=1,r=1;
  5.         for(int i=0;i<n;i++){
  6.             l=(l?l:1)*nums[i];
  7.             r=(r?r:1)*nums[n-1-i];
  8.             ans=max({ans,l,r});
  9.         }
  10.         return ans;
  11.     }
  12. };
  13.  
  14. -----------------
  15.  
  16. class Solution {
  17. public:
  18.     int maxProduct(vector<int>& nums) {
  19.         int product = nums[0], maxProduct = product, minProduct = product;
  20.        
  21.         for(int i=1; i<nums.size(); i++){
  22.             int tmp = max(nums[i], max(maxProduct*nums[i], minProduct*nums[i]));
  23.             minProduct = min(nums[i], min(maxProduct*nums[i], minProduct*nums[i]));
  24.             maxProduct = tmp;
  25.             product = max(maxProduct, product);    
  26.         }
  27.         return product;
  28.     }
  29. };
RAW Paste Data