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
CodePudding user response:
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