gpt4 book ai didi

c++ - 找到最大的连续子序列总和的开始和结束

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:46:41 26 4
gpt4 key购买 nike

这是我寻找最大最大连续子序列和的程序。我能够计算总和。如何修改此代码以找到此最大子序列总和的开始和结束索引?

int maxSubArraySum(int a[], int size)
{
int final_max = 0, curr_max = 0;
for (int i = 0; i < size; i++)
{
curr_max = curr_max + a[i];
if (curr_max < 0)
curr_max = 0;

else if (final_max < curr_max)
final_max = curr_max;
}
return final_max;
}

最佳答案

您只需要记住求和开始和结束的索引即可。

struct SumAndRange{
int sum;
int start;
int stop;
SumAndRange() : sum(0),start(0),stop(0) {}
};

SumAndRange maxSubArraySum(int a[], int size) {
SumAndRange curr; // we will start with the sum of the first element
SumAndRange final;
for (int i = 0; i < size; i++) {
curr.sum = curr.sum + a[i];
if (curr.sum < 0) { // if we reset the sum it will
curr.sum = 0; // start with the next index
curr.start = i+1;
curr.stop = i+1; // ...and we also handle the case of
// the sum is only one element

} else { // otherwise the sum continues with
curr.stop = i; // this index
if (final.sum < curr.sum) { final = curr; }
}
}
return final;
}

int main() {
int a[] = { 2,-6,7,-3,12};
SumAndRange sar = maxSubArraySum(a,5);
std::cout << sar.sum << " " << sar.start << " " << sar.stop << std::endl;
return 0;
}

关于c++ - 找到最大的连续子序列总和的开始和结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36921720/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com