Bloomberg 05102012 [1]

本文介绍了一个寻找整数数组中包含正负数的最大子序列和的算法,并返回该子序列在原数组中的起始和结束索引。示例中使用了具体数组进行演示,展示了如何确定最大子序列及其位置。
/*
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;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值