classSolution{public:intmaxProduct(vector<int>&nums){intn=nums.size();// We need a variable to store the maximum product found so far// We initialize it with the first number, as a single number is a valid subarrayintmaxProductFound=nums[0];// This first loop selects the starting point of our subarrayfor(inti=0;i<n;i++){// This variable will store the product of the current subarray that starts at 'i'// We must reset it to 1 for each new starting pointintcurrentProduct=1;// It moves the 'end' of the subarray from 'i' to the end of the arrayfor(intj=i;j<n;j++){// We multiply the numbers in the current subarray [i...j]currentProduct*=nums[j];// If the product of the current subarray is the biggest we've seen,// we update our answermaxProductFound=max(maxProductFound,currentProduct);}}returnmaxProductFound;}};
classSolution{public:intmaxProduct(vector<int>&nums){intn=nums.size();intresult=nums[0];// It will store our maximum product so farintproductMax=nums[0];// This will be the maximum product till `i`intproductMin=nums[0];// This will be the minimum product till `i`// We iterate through complete arrayfor(inti=1;i<n;i++){inttempMax=productMax;// Cause, actual productMax value will be needed to find productMin// 1. Start with this new subarray// 2. Extend this subarray by, using max product// 3. Extend this subarray by, using min product (-ve * -ve = big +ve)productMax=max({nums[i],nums[i]*tempMax,nums[i]*productMin});// same for `productMin`productMin=min({nums[i],nums[i]*tempMax,nums[i]*productMin});result=max(result,productMax);// Whoever is bigger, take it}returnresult;}};
Warning
LINK
You are about to visit a link which has been flagged with the above content warnings. Do you wish to continue?