软件工程第三次作业

求最大连续子数组和(最大子段和)

算法设计

   一个数组arr,求它的最大连续子数组的和,使用currentSum来计算当前连续子数组的和,如果currentSum小于0,那么无论后面再加上什么数字都只会让子数组变小,所以抛弃当前子数组,重新开始计算子数组的值。算法流程图如图1。

![](https://img2018.cnblogs.com/blog/1644408/201904/1644408-20190416194345668-2050294096.png)
**图1**
## 算法编码实现    [Coding 地址][1]

   算法实现如下:

public class MaxSubArray {
	// 求数组最大连续子数组的和
	public static int getMaxSubArray(int[] arr) {
		
		int len = arr.length;// 数组大小
		int maxSum = 0; // 记录子数组的和
		int currentSum = 0; // 当前子数组的和
		int low = 0; // 记录子数组的最低位下标
		int height = 0; // 记录子数组的最高位下标
		
		for (int i = 0; i < len; i++) {
			currentSum += arr[i];
			if (currentSum > maxSum) {
				maxSum = currentSum;
				height = i;
			} else if (currentSum <= 0) {
				currentSum = 0;
				low = i + 1;
			}

		}
		
		System.out.println("最大连续子数组下标" + low + "-" + height + " 最大连续子数组和:" + maxSum);
		return maxSum;
	}

	
}

测试

条件组合覆盖测试

   满足“条件组合覆盖”的测试用例是一定满足判定覆盖、条件覆盖、判定/条件覆盖的。由于我的代码每个if语句只有一个判断项,在设计测试用例的时候很容易达到条件组合覆盖。测试代码如下:

	public class test {

	@Test
	public void testGetMaxSubArray1() {
		int[] arr1 = {1, 4, -5, 9, 8, 3, -6};
		assertEquals(20, MaxSubArray.getMaxSubArray(arr1));
	}
	@Test
	public void testGetMaxSubArray2() {
		int[] arr2 = {1, -2, 3, 10, -4, 7, 2, -5};
		assertEquals(18, MaxSubArray.getMaxSubArray(arr2));
	}

}

   测试结果截图:

![](https://img2018.cnblogs.com/blog/1644408/201904/1644408-20190416201859811-408714918.png)
**图2**
![](https://img2018.cnblogs.com/blog/1644408/201904/1644408-20190416201913980-1310051071.png)
**图3**
原文地址:https://www.cnblogs.com/jiaorenzhan/p/10719463.html