现在的位置: 首页 > 综合 > 正文

最大连续子数组和

2018年01月17日 ⁄ 综合 ⁄ 共 393字 ⁄ 字号 评论关闭
#include <iostream>
#include <algorithm>
using namespace std;

int a[] = {
	1, -2, 3, 10, -4, 7, 2, -5
};

int opt[20];

int main(void)
{
	memset(opt, 0, sizeof(opt));
	int maxv = -1;
	int rhs, lhs;
	opt[0] = a[0];
	for(int i = 1; i < 8; ++i)
		opt[i] = max(a[i], a[i] + opt[i-1]);	
	
	for(int j = 0; j < 8; ++j)
	{
		if(maxv < opt[j])
		{
			maxv = opt[j];
			rhs = j;
		}	
	}
	cout << a[rhs] <<endl;
	for(lhs = rhs; lhs >= 0; --lhs)
	{
		if(opt[lhs] < 0)
			break;
	}
	lhs++;

	cout << maxv << endl << lhs << " " << rhs << endl;
	
	return 0;
}

【上篇】
【下篇】

抱歉!评论已关闭.