-1

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;
    }
24n8
  • 1,898
  • 1
  • 12
  • 25

1 Answers1

2

The two blocks of code are not equivalent.

if(nums[i] < 0) {
    max_num = std::max(nums[i], min_num*nums[i]);
    min_num = std::min(nums[i], max_num*nums[i]); // This uses modified max_num.
}

I'm fairly certain that is a bug. If you change it to

if(nums[i] < 0) {
    auto temp = std::max(nums[i], min_num*nums[i]);
    min_num = std::min(nums[i], max_num*nums[i]);  // This uses unmodified max_num
    max_num = temp;
}

then they will be equivalent.

R Sahu
  • 204,454
  • 14
  • 159
  • 270