I am solving https://leetcode.com/problems/maximum-product-subarray/submissions/
I have 2 solutions to this problem, and I believe they are equivalent. However, I obtain the error
Line 24: Char 52: runtime error: signed integer overflow: -944784000 * 4 cannot be represented in type 'int' (solution.cpp)
for the first code for certain large inputs, but I do not for the second one. I don't think there is any functional difference between the 2 codes, so why is the first one overflowing?
Code 1
int maxProduct(vector<int>& nums) {
if(nums.empty()) return 0;
auto n = nums.size();
int min_num = nums[0];
int max_num = nums[0];
int curr_max = nums[0];
for(int i = 1; i < n; i++)
{
if(nums[i] < 0) {
max_num = std::max(nums[i], min_num*nums[i]);
min_num = std::min(nums[i], max_num*nums[i]);
}
else
{
max_num = std::max(nums[i], max_num*nums[i]);
min_num = std::min(nums[i], min_num*nums[i]);
}
curr_max = std::max(curr_max, max_num);
}
return curr_max;
}
Code 2
int maxProduct(vector<int>& nums) {
if(nums.empty()) return 0;
auto n = nums.size();
int min_num = nums[0];
int max_num = nums[0];
int curr_max = nums[0];
for(int i = 1; i < n; i++)
{
if(nums[i] < 0) std::swap(max_num,min_num);
max_num = std::max(nums[i], max_num*nums[i]);
min_num = std::min(nums[i], min_num*nums[i]);
curr_max = std::max(curr_max, max_num);
}
return curr_max;
}