/*
Find the maximum subsequence sum of an array of integers which contains both positive and negative numbers and return the starting and ending indices within the array.
For example:
int array[] = {1, -2, -3, 4, 5, 7, -6}
The max subsquence sum is 4+5+7= 16 and start index is at 3 and end index is at 5.
*/
#include <iostream>
int main()
{
int left = 0;
int right = 0;
int curLeft = 0;
int curRight = 0;
int maxSum = 0;
int curSum = 0;
int a[] = {1, -2, -3, 4, 5, 7, -6};
for(int i = 0; i < 7; i++)
{
curSum += a[i];
if(curSum > maxSum)
{
curRight = i;
left = curLeft;
right = curRight;
maxSum = curSum;
}
if(curSum <= 0)
{
curSum = 0;
curLeft = i + 1;
}
}
printf("From: %d To: %d\n", left, right);
printf("Max Sum: %d\n", maxSum);
for(int i = left; i <= right; i++)
{
printf("%d ", a[i]);
}
return 0;
}Bloomberg 05102012 [1]
最新推荐文章于 2021-11-11 02:52:09 发布
本文介绍了一个寻找整数数组中包含正负数的最大子序列和的算法,并返回该子序列在原数组中的起始和结束索引。示例中使用了具体数组进行演示,展示了如何确定最大子序列及其位置。
1万+

被折叠的 条评论
为什么被折叠?



