您的位置:首页 > 其它

动态规划--求最大连续子串之和

2016-11-15 23:08 211 查看
给定由n个整数(可能为负整数)组成的序列A1,A2,A3,…,An,求该序列的连续子段的和的最大值。

例如 {-4, 11,-2, 13,-7,-3,12} 的最大子段和为24

JAVA代码实现:

package com.example;

public class 最大连续子串之和 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a = {-4, 11, -2, 13, -7,- 3, 12} ;
getMaxSumSeq(a);
}

private static void getMaxSumSeq(int[] a){
int rmax = Integer.MIN_VALUE;
int sum = Integer.MIN_VALUE;
int start = -1;
int end = -1;
int temp = -1;
for(int i = 0 ;i<a.length;i++)
{
if(sum>0)
{
sum+=a[i];
}
else
{
sum = a[i];
temp = i;
}
if(sum>rmax)
{
start = temp;
rmax= sum;
end = i;
}
}
for(int j = start;j<=end;j++)
{
System.out.print(a[j]+" ");
}
System.out.println("\nsum:"+rmax);
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息