-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhighestProductOf3.cpp
More file actions
52 lines (40 loc) · 1.05 KB
/
highestProductOf3.cpp
File metadata and controls
52 lines (40 loc) · 1.05 KB
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
49
50
51
52
#include <vector>
using namespace std;
int highestProductOf3(const vector<int>& vectorOfInts) {
if (vectorOfInts.size() < 3) {
throw invalid_argument("Error: Ya need three numbers to get "
"a product of 3, mate");
}
int highest = max(vectorOfInts[0], vectorOfInts[1]);
int lowest = min(vectorOfInts[0], vectorOfInts[1]);
int highestProductOf2 = vectorOfInts[0] * vectorOfInts[1];
int lowestProductOf2 = vectorOfInts[0] * vectorOfInts[1];
int highestProductOf3 = vectorOfInts[0] * vectorOfInts[1] * vectorOfInts[2];
for (size_t i = 2; i < vectorOfInts.size(); ++i) {
int current = vectorOfInts[i];
highestProductOf3 = max(
highestProductOf3,
max(
current * highestProductOf2,
current * lowestProductOf2
)
);
lowestProductOf2 = min(
lowestProductOf2,
min(
current * highest,
current * lowest
)
);
highestProductOf2 = max(
highestProductOf2,
max(
current * highest,
current * lowest
)
);
lowest = min(lowest, current);
highest = max(highest, current);
}
return highestProductOf3;
}