最大字段和

题目要求

问题: 给定n个整数(可能为负数)组成的序列a[1],a[2],a[3],…,a[n],求该序列如a[i]+a[i+1]+…+a[j]的子段和的最大值。当所给的整数均为负数时定义子段和为0,依此定义,所求的最优值为: Max{0,a[i]+a[i+1]+…+a[j]},1<=i<=j<=n
例如,当(a[1],a[2],a[3],a[4],a[5],a[6])=(-2,11,-4,13,-5,-2)时,最大子段和为20。


代码

package zuoye3;

public class zuoye3 {
	public int maxSum(int arr[]) {
		int n = arr.length,sum = 0;
		for(int i = 1;i <= n;i++) {
			int thissum = 0;
			for(int j = i;j <= n;j++) {
				thissum += arr[j - 1];
				if(thissum > sum) {
					sum = thissum;
				}
			}
		}
		return sum;
	}
}


测试类

package zuoye3;

import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;

class sumtest {

	@Test
	public void test1() {
		int[] a=new int[] {-1,0,7,2,8,-3};
		assertEquals(17,new zuoye3().maxSum(a));
	}
	
	@Test
	public void test2() {
		int[] a=new int[] {-1,-2,-3,-4,-5,-6};
		assertEquals(0,new zuoye3().maxSum(a));
	}

}


测试结果如下

  • 测试结果正确
posted @ 2018-03-29 21:14  佳肴  阅读(153)  评论(0)    收藏  举报