'How do I find the biggest possible product of two numbers in an array in C++?
#include <iostream>
using namespace std;
int main()
{
int product;
int n;
int num1;
int num2;
cout << "Enter the number of numbers you'll input: ";
cin >> n;
int numbers[n];
for(int i = 0; i < n; i++){
cout << "";
cin >> numbers[i];
}
for(int i = 0; i < n; i++){
for(int m = 0; m < n; m++){
if(i != m){
product = numbers[m] * numbers[i];
if(product < numbers[m - 1] * numbers[i] && i != m - 1){
product = numbers[m - 1] * numbers[i];
num1 = numbers[m - 1];
num2 = numbers[i];
}
}
}
}
cout << "" << num1 << " " << num2 << "" << endl;
return 0;
}
This is what I've been able to do so far. Sometimes it works fine and sometimes it doesn't. It depends on the order of the numbers. I noticed that the product is the correct value but when I print the two numbers that get multiplied they aren't correct.
I want it to print the two numbers.
Solution 1:[1]
In your example you overwrite the product without checking and also you constantly calculate products regardless. Just go through the Array once, on your way you compare for the smallest two negative numbers and same time for the largest positive numbers. In the end you are left with the factors forming the largest possible product from either direction, this you only have to compare and automatically you held your factors too.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | FranzBranntwein |
