Created
October 17, 2015 22:46
-
-
Save goldsborough/19465c9b41eb9e6bdb1a to your computer and use it in GitHub Desktop.
Super-short algorithm to find the maximum subarray.
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
template<typename Iterator> | |
auto maximum_subarray(Iterator begin, Iterator end) -> decltype(*begin + *begin) | |
{ | |
using T = decltype(*begin + *begin); | |
T sum = 0; | |
T best = 0; | |
auto largest = end; | |
for ( ; begin != end; ++begin) | |
{ | |
sum += *begin; | |
if (largest == end || *begin > *largest) largest = begin; | |
if (sum > best) best = sum; | |
else if (sum < 0) sum = 0; | |
} | |
// in std::max(largest, best) best (at least 0) | |
// would win if largest is negative | |
if (*largest < 0) return *largest; | |
return best; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment