这是我的程序,用于从给定数组中找到子数组(连续)的最大和。使用 kadane 的算法非常容易。
#include <iostream>
#include <cstdio>
using namespace std;
int kadane(int a[], int n) {
int max_ending_here = a[0], max_till_now = a[0];
int _start = 0, _end;
bool s=true;
for (int i = 1; i < n; ++i)
{
max_ending_here = max(a[i], max_ending_here + a[i]);
if(max_ending_here + a[i] > a[i] && s==false) _start = i, s=true;
max_till_now = max(max_ending_here, max_till_now);
if(max_ending_here + a[i] < a[i] && s==true) _end=i-1,s=false;
}
printf("S = %d , E = %d\n",_start,_end);
return max_till_now;
}
int main(int argc, char const *argv[])
{
//int a[10] = {1,-3,2,-5,7,6,-1,-4,11,-23};
int a[6] = {-8,-1,-1,-1,-1,-5};
int m = kadane(a, 6);
printf("%d\n",m);
return 0;
}
但我也想找到具有最大总和的连续子数组的开始和结束位置。我尝试在上面的程序中添加几行来做到这一点,但它没有用。所以我的问题是如何获得具有最大总和的子数组的开始和结束位置?谢谢。