Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why isn't my C++ maximizing pairwise product code working?

So the problem asked me to find the greatest product from a given sequence of non-negative integers. What I did was I tried to find the greatest two integers from the sequence (for which I used a vector, by taking an input of n numbers) and multiplied them, since there are no negative integers. I used the long long type as well, since just an int type would not be enough for huge numbers. I kept getting a random huge number as the output whenever I tried to run the program :

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

long long max_prod(const vector<int>& numbers) {
    int max1 = -1;
    int max2 = -1;
    int n = numbers.size();
    for (int i = 0; i<n; i++){
        if (numbers[i] > numbers[max1]) 
            max1 = i;
    }
    for (int j = 0; j < n; j++) {
        if (numbers[j] > numbers[max2] && j!=max1)
            max2 = j;
    }
return ((long long)(numbers[max1])) * ((long long)(numbers[max2]));
}

int main(){
    int n;
    cin >> n;
    vector<int> numbers(n);
    for (int i = 0; i<n; i++){
        cin >> numbers[i];
    }
    long long result = max_prod(numbers);
    cout << result << "\n";
    return 0;
}

the last line is the output given by the program

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You haver undefined behavior right here

long long max_prod(const vector<int>& numbers) {
    int max1 = -1; <<<<<====
    int max2 = -1;
    int n = numbers.size();
    for (int i = 0; i < n; i++) {
        if (numbers[i] > numbers[max1]) <<<<<==
            max1 = i;
    }
    for (int j = 0; j < n; j++) {
        if (numbers[j] > numbers[max2] && j != max1)
            max2 = j;
    }
    return ((long long)(numbers[max1])) * ((long long)(numbers[max2]));
}

You try to access numbers[-1] (twice once in the j loop and once in the i loop).

Set maxi and maxj to 0

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading