最大连续子数组和(最大子段和)
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。
代码:
package max_member;
public class Max_member {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] Members = {-2,11,-4,13,-5,-2};
int Max = Select_max(Members);
System.out.println("连续子数组之最大和为:"+Max);
}
public static int Select_max(int[] Members) {
if (Members.length==0 || Members==null) {
return 0;
}
int Sum = 0;
int max = 0;
for (int i = 0; i < Members.length; i++) {
if(Sum<=0){
Sum = Members[i];
}
else{
Sum += Members[i];
}
if(Sum>max){
max = Sum;
}
}
return max;
}
}
2.单元测试选择:条件组合覆盖
覆盖标准:
使每个判定中条件的各种可能组合都至少出现一次
条件选择的程序流程图如下:
条件组合 | 执行路径 |
---|---|
sum<=0,sum>max | abdef |
sum>0,sum>max | acdef |
sum>0,sum>=max | acdf |
sum<=0,sum>=max | abdf |
测试数据只需要一组[5,9,-6,3]即可实现上述四种执行路径
3.测试
代码:
package max_member;
import static org.junit.Assert.*;
import org.junit.Test;
public class test {
@Test
public void testSelect_max() {
int[] arr={5,9,-6,3};
assertEquals(3,Max_member.Select_max(arr));
}
}