题目要求
题目(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。
1. 需要测试的类的代码及截图:
代码如下:
package wang.test;
public class GetMaxSubArray {
public static void main(String[] args) {
int[] array = {-2,-11,-4,13,-5,-5,-2};
int result = maxSubArray(array);
System.out.println("连续子数组之最大和为:"+result);
}
public static int maxSubArray(int[] array) {
if (array.length==0 || array==null)
return 0;
int current = 0;
int max = 0;
for (int i = 0; i < array.length; i++) {
if(current<=0)
current = array[i];
else
current += array[i];
if(current>max)
max = current;
}
return max;
}
}
eclipse截图:
2. 测试类的代码及截图:
代码如下:
package wang.test;
import static org.junit.Assert.assertEquals;
import org.junit.jupiter.api.Test;
public class TestGetMaxSubArray {
@Test
public void testMaxSubArray() {
int[] a = new int[] {1,-11,23,-1,35,-3};
assertEquals(57,new GetMaxSubArray().maxSubArray(a));
}
}
eclipse截图: