Created
November 15, 2015 02:34
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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