eg. -2, 1, -3, 4, -1, 2, 1, -5, 4 => (4 -1 2 1)
<pre name="code" class="cpp">
#include <iostream>
#include <vector>
#include <memory>
#include <utility>
//#include <>
void max_sub(int *a, int n)
{
std::vector<std::pair<int, int>> re;
for (int i = 0; i < n; i++)
{
int max_sum = 0;
int len = 0;
for (int j = i, tmp_sum = 0; j < n; j++)
{
tmp_sum += a[j];
if (max_sum <= tmp_sum){
max_sum = tmp_sum;
len = j-i+1;
}
}//for
re.push_back(std::make_pair(len,max_sum));
}//for
// all max sum
std::vector<int> maxsum_idx;
for (int i = 1, max=re[0].second; i < n; i++){
if (re[i].second > max){
max = re[i].second;
maxsum_idx.clear();
maxsum_idx.push_back(i);
}
if (re[i].second == max){
max = re[i].second;
maxsum_idx.push_back(i);
}
}
// a max len in the set of max sum
int maxlen = 0;
int pos;
for (auto i : maxsum_idx){
if (re[i].first > maxlen){
maxlen = re[i].first;
pos = i;
}
}
std::cout << pos <<" "<< maxlen << std::endl;
for (int i = pos; i < maxlen + pos; i++){
std::cout << a[i] << ' ';
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int a[] = { -2, 1, -3, 4, -1, 2, 1, 1, -1, -5, 4 };
max_sub(a, 16);
return 0;
}