Skip to content

Instantly share code, notes, and snippets.

@goldsborough
Created October 17, 2015 22:46
Show Gist options
  • Save goldsborough/19465c9b41eb9e6bdb1a to your computer and use it in GitHub Desktop.
Save goldsborough/19465c9b41eb9e6bdb1a to your computer and use it in GitHub Desktop.
Super-short algorithm to find the maximum subarray.
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