使用暴力求解法,算出所有子数组的和,比较大小,得出结果,代码如下
1 package cn.edu.niit.test2; 2 3 /** 4 * Created by Wang Yifan on 2017/03/17. 5 */ 6 7 public class Test2 { 8 int MaxSubArray(int[] A, int n) 9 { 10 int maxSum = A[0]; //全负情况,返回最大负数 11 int currSum = 0; 12 for (int i = 0; i < n; i++) 13 { 14 for (int j = i; j < n; j++) 15 { 16 for (int k = i; k <= j; k++) 17 { 18 currSum += A[k]; 19 } 20 if (currSum > maxSum) 21 maxSum = currSum; 22 23 currSum = 0; 24 } 25 } 26 return maxSum; 27 } 28 }
对此方法进行测试,验证算法是否正确,代码如下
1 package cn.edu.niit.test2; 2 3 import org.junit.Before; 4 import org.junit.Test; 5 6 import static org.junit.Assert.*; 7 8 /** 9 * Created by Wang Yifan on 2017/03/17. 10 */ 11 12 public class Test2Test { 13 private Test2 Array; 14 15 @Before 16 public void setUp() throws Exception { 17 Array = new Test2(); 18 } 19 20 @Test 21 public void maxSubArray() throws Exception { 22 int []Array1={-1,2,3,-4}; 23 assertEquals(5d,Array.MaxSubArray(Array1,Array1.length),4); 24 25 int []Array2={-1,2,-5,3,-4}; 26 assertEquals(3d,Array.MaxSubArray(Array2,Array2.length),5); 27 28 int []Array3={-1,20,-5,30,-4}; 29 assertEquals(45d,Array.MaxSubArray(Array3,Array3.length),5); 30 31 int []Array4={-2,-3,-5,-1,-9}; 32 assertEquals(-1d,Array.MaxSubArray(Array4,Array4.length),5); 33 } 34 }
验证结果如下图,算法正确