您的位置:首页 > 其它

算法:最大子数组own

2015-08-13 12:04 260 查看
转载标明出处:http://i.cnblogs.com/EditPosts.aspx?postid=4726782&update=1

暴力法:

// Max_Value.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;

int Max(int *a,int low,int high,int &sub_left,int &sub_right,int &sub_sum)
{
if (low==high)
{
if (a[low]>0)
{
sub_sum=a[low];
sub_left=low;
sub_right=high;
}
else sub_sum=0;
}
int tempSum=0;
for (int i=low;i<=high;i++)
{
tempSum+=a[i];
if (tempSum<=0)
{
tempSum=0;
sub_left=i+1;
}
if (tempSum>sub_sum)
{
sub_sum=tempSum;
sub_right=i;
}
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
int sub_left=0;
int sub_right=0;
int sub_sum=0;
int a[]={13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7};
Max(a,0,15,sub_left,sub_right,sub_sum);
cout<<sub_left<<" "<<sub_right<<" "<<sub_sum<<endl;
system("pause");
return 0;
}


View Code
只扫描了一遍,时间复杂度为O(n);

以上方法输出结果都一样:7 10 43
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: