码迷,mamicode.com
首页 > 编程语言 > 详细

AS 数组内两个最大的和

时间:2017-03-17 23:41:01      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:清零   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);
}
}

AS 数组内两个最大的和

标签:清零   arrays   equal   equals   sum   max   test   否则   subarray   

原文地址:http://www.cnblogs.com/xuzhinan/p/6569025.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!