-
Notifications
You must be signed in to change notification settings - Fork 0
/
MaximumPairwiseProduct.cpp
48 lines (40 loc) · 1.1 KB
/
MaximumPairwiseProduct.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <vector>
using std::vector;
using std::cin;
using std::cout;
long long MaxPairwiseProduct(const vector<int>& numbers) {
long long result = 0;
int n = numbers.size();
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
if (((long long)numbers[i]) * numbers[j] > result) {
result = ((long long)numbers[i]) * numbers[j];
}
}
}
return result;
}
long long MaxPairwiseProductFast(const vector<int>& numbers) {
int n = numbers.size();
int max_index1 = -1;
for (int i = 0; i < n; ++i)
if ((max_index1 == -1) || (numbers[i] > numbers[max_index1]))
max_index1 = i;
int max_index2 = -1;
for (int j = 0; j < n; ++j)
if ((j != max_index1) && ((max_index2 == -1) || (numbers[j] > numbers[max_index2])))
max_index2 = j;
return ((long long)(numbers[max_index1])) * numbers[max_index2];
}
int main() {
int n;
cin >> n;
vector<int> numbers(n);
for (int i = 0; i < n; ++i) {
cin >> numbers[i];
}
long long result = MaxPairwiseProductFast(numbers);
cout << result << "\n";
return 0;
}