Why is this code not working for this Problem?
Why is this code not working for this Problem?
Because your approach is wrong.
and also it fails for almost every testcase, few examples being
5
0 1 2 3 5
5
0 1 2 3 0
Correct Appoach
int maxProduct(vector<int>& nums) {
if(nums.empty())
return 0;
int ans = nums[0];
int mx = nums[0], mn = nums[0], n = nums.size();
for(int i = 1; i < n; i++){
if(nums[i]<0)
swap(mx,mn);
mx = max(mx*nums[i],nums[i]);
mn = min(mn*nums[i],nums[i]);
ans = max({ans,mx});
}
return ans;
}