求数组最大子数组和
(1).题目描述
给定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。 -- 引用自
(2).功能函数:
//求最大子数组和 public static int maxarraysum(int[] array) { int maxsum = 0; //最大和 int sum = 0; //记录子串的和 for(int i = 0; i < array.length; i++) { sum += array[i]; if(sum > maxsum) { maxsum = sum; }else if(sum < 0) { //子串和为0则应丢弃,,子串和赋0值 sum = 0; } } return maxsum; }
(3).流程图
(4).单元测试
本次单元测试采用判定条件覆盖,
条件组合 | 程序执行路径 |
---|---|
sum > maxsum | abfg |
sum < maxsum,sum<0 | acdg |
sum < maxsum,sum>0 | aceg |
选取三组测试用例,测试用例如下
{2,4,6,2,4,8,9} {-2,-4,-6,-2,-4,-8,-9} {10,-2,-1,-2,-3}测试类:
public class MaxarraysumTest { @Test public void testMaxarraysum() { int[] array_1 = {2,4,6,2,4,8,9}; int[] array_2 = {-2,-4,-6,-2,-4,-8,-9}; int[] array_3 = {10,-2,-1,-2,-3}; assertEquals(35, new MaxSubArray().maxarraysum(array_1)); assertEquals(0, new MaxSubArray().maxarraysum(array_2)); assertEquals(10, new MaxSubArray().maxarraysum(array_3)); }}