C++ Max Product Of Three
#include <algorithm>
#include <vector>
long long maxProductOfThree(std::vector<int> a)
{
std::sort(a.begin(), a.end());
int c = static_cast<int>(a.size());
long long topThree = static_cast<long long>(a[c - 1]) * a[c - 2] * a[c - 3];
long long twoLowestAndTop = static_cast<long long>(a[0]) * a[1] * a[c - 1];
return std::max(topThree, twoLowestAndTop);
}
This checks the useful extremes, because the best product can come from either the three largest numbers or two negatives plus one large positive.