cppintermediate10 minutes

Fix Bug in C++ Function to Find Maximum Product of Two Elements

The provided C++ function is intended to find the maximum product of any two distinct elements in an integer array. However, it contains logical and implementation bugs that lead to incorrect results or runtime errors. Your task is to identify and fix these bugs to ensure the function works correctly for all valid inputs.

Challenge prompt

Given a vector of integers, complete the function maxProduct that returns the maximum product of any two distinct elements. The current implementation contains bugs—some related to loop bounds and some related to handling edge cases. Fix the code so it correctly computes the maximum product for any input array with at least two elements.

Guidance

  • Check the loop boundaries to ensure you are iterating over all pairs of elements without accessing out-of-bound indices.
  • Make sure to handle negative numbers correctly since the product could be maximal using two negative values.
  • Avoid using the same element twice by ensuring the pair indices are distinct.

Hints

  • Look closely at the conditions in the nested loops and the initialization of the max product variable.
  • Consider what happens if the input array contains negative numbers or zeros.

Starter code

#include <vector>
#include <iostream>
using namespace std;

int maxProduct(const vector<int>& nums) {
    int max_prod = INT_MIN;
    for (int i = 0; i <= nums.size(); ++i) {
        for (int j = i; j < nums.size(); ++j) {
            if (i != j && nums[i] * nums[j] > max_prod) {
                max_prod = nums[i] * nums[j];
            }
        }
    }
    return max_prod;
}

int main() {
    vector<int> nums = {3, -4, 2, -5, 1};
    cout << maxProduct(nums) << endl;
    return 0;
}

Expected output

-10

Core concepts

nested loopsarray indexingedge case handlingloop boundaries

Challenge a Friend

Send this duel to someone else and see if they can solve it.