int maxProduct(vector<int>& nums) {
int lastMin = nums.front(), lastMax = nums.front(), result = lastMax;
for(int i = 1; i<nums.size(); i++) {
int tempMin = lastMin, tempMax = lastMax;
lastMin = min(nums[i], min(tempMin * nums[i], tempMax * nums[i]));
lastMax = max(nums[i], max(tempMin * nums[i], tempMax * nums[i]));
result = max(result, lastMax);
}
return result;
}
Simple 4ms C++ solution


My code works perfectly same as what other people do. What I did here is just optimize space complexity. Every iteration, we need to look into min & max values calculated just before. So, I just used two variables (lastMin and lastMax) instead of using n size of array. (Actually, 2n because we need to keep track of minimum and maximum values)