Skip to content

Instantly share code, notes, and snippets.

@goldsborough
Created November 15, 2015 02:34
Show Gist options
  • Save goldsborough/6898e9d108dd0fe9bf2f to your computer and use it in GitHub Desktop.
Save goldsborough/6898e9d108dd0fe9bf2f to your computer and use it in GitHub Desktop.
Computes the largest product of N numbers in a of a sequence of N or more numbers.
int largest_product_of_n(std::vector<int> values, std::size_t n)
{
if (values.size() < n)
{
throw std::invalid_argument("Sequence size must at least n!");
}
std::sort(values.begin(), values.end());
int positive_product = 1;
for (std::size_t count = 0, i = values.size() - 1; count < n; ++count, --i)
{
positive_product *= values[i];
}
if (values[1] >= 0) return positive_product;
int negative_product = 1;
int last_negative = 0;
std::size_t i = 0;
for ( ; i < n; ++i)
{
if (values[i] >= 0) break;
if (last_negative == 0)
{
last_negative = values[i];
}
else
{
negative_product *= last_negative * values[i];
last_negative = 0;
}
}
if (last_negative != 0) --i;
for (std::size_t j = values.size() - 1; i < n; ++i, --j)
{
negative_product *= values[j];
}
return std::max(positive_product, negative_product);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment