标签:清零 arrays equal equals sum max test 否则 subarray
public class Arrays {
int MaxSubArray(int[] A, int n)
{
int maxSum =A[0];
int currSum = 0;
for (int i = 0; i < n; i++)
{
for (int j = i; j < n; j++)
{
for (int k = i; k <= j; k++)
{
currSum += A[k];
}
if (currSum > maxSum)
maxSum = currSum;
currSum = 0; //这里要记得清零,否则的话sum最终存放的是所有子数组的和。
}
}
return maxSum;
}
}
public class ArraysTest {
private Arrays Array;
@Before
public void setUp() throws Exception {
Array = new Test2();
}
@Test
public void maxSubArray() throws Exception {
int []array1={-1,2,9,-4};
assertEquals(11d,Array.MaxSubArray(array1,array1.length),4);
int []array2={-1,2,3,3,-4};
assertEquals(8d,Array.MaxSubArray(array2,array2.length),5);
int []array3={-1,20,10,30,-4};
assertEquals(60d,Array.MaxSubArray(array3,array3.length),5);
int []array={-2,-3,-5,-1,-9};
assertEquals(-1d,Array.MaxSubArray(array,array.length),5);
}
}
标签:清零 arrays equal equals sum max test 否则 subarray
原文地址:http://www.cnblogs.com/xuzhinan/p/6569025.html