Largest Subarray
/**
* Find the continuous sequence with the largest sum in a array.
*/
/*
The Algorithm:
- First cut off negative edges on the right and left hand side of
the array. The intuition is that starting or ending with an
negative number cannot do us any good in finding the max
continous sum.
- Iterate from left to right. As we go along, we measure a cur_max
which is a local maximum from a particular substring starting
from a positive integer. Once the sequence hits less than a cumulative
sum that is less than zero, we know that it is equivalent to
starting from a negative number. Starting from any positive number is better.
I.e. we cannot only benefit from positive numbers.
- As we go, we also maintain a final_max, that records the maximums as we
go along in the array.
*/
template<typename iter>
int next_positive_i(iter begin, iter end, int start_i)
{
int count = start_i;
for (iter i = begin + start_i; i != end; i++) {
if (*i > 0) return count;
count++;
}
}
int sum_max_subarray(const vector<int> &elements)
{
// rid of first negatives
int memory_positive = next_positive_i(elements.begin(), elements.end(), 0);
int end_stop = elements.size()
- next_positive_i(elements.rbegin(), elements.rend(), 0);
int cur_max = 0;
int final_max = 0;
for (int i = memory_positive; i < end_stop; i++)
{
cur_max += elements[i];
final_max = max(cur_max, final_max);
if (cur_max < 0) {
i = next_positive_i(elements.begin(), elements.end(), memory_positive + 1) - 1;
memory_positive = i;
cur_max = 0;
}
}
return final_max;
}
int main()
{
// return 6
cout << sum_max_subarray(vector<int>() = { -2, 1, -3, 4, -1, 2, 1, -5, 4 }) << endl;
// return 7
cout << sum_max_subarray(vector<int>() = { -2, -3, 4, -1, -2, 1, 5, -3 }) << endl;
}
Last updated