Ali Abdel Samie - 8 months ago 38

C++ Question

i tried to find the max product of 2 array element so my idea is to sort the array and multiply the last 2 elements. my code is working with different test cases but in test case .

2

100000 90000

it has wrong answer only in this test case !

Here is my code

`#include <iostream>`

#include<algorithm>

using namespace std;

int main()

{

int n;

cin >> n ;

int arr [n];

for (int i=0; i<n; i++)

cin>> arr[i] ;

for (int i=0; i<n; i++)

for(int j=i+1; j<=n; j++)

if (arr[j]<arr[i])

swap(arr[j],arr[i]) ;

cout <<arr[n-1]<<" "<<arr[n-2] <<endl;

int res = arr[n-1] * arr[n-2];

cout << res ;

}

Answer

The following code should work:

```
#include <vector>
#include <algorithm>
#include <iostream>
int main()
{
int num = 0, size = 0;
std::cin >> size;
std::vector<int> numbers(size);
for (int counter = 0; counter < size; counter++) {
std::cin >> num;
numbers[counter] = num;
}
std::sort(numbers.begin(), numbers.end());
int max = numbers[size - 1] * numbers[size - 2];
std::cout << max << std::endl;
}
```

Since you are utilizing *Variable Length Arrays*, why not just use a vector?

The code above gets numbers from `std::cin`

, and puts them into the vector. The vector is then sorted. We have a variable for the size of `vector - 1`

, so we don't go out of bounds accessing our elements. `max`

is the initialized to the product of the last two elements of the vector. Finally, the product gets printed.