求数组最大子数组和

package yunsuan;

public class Array {
public static void main(String[] args) {

int[] a = { 1, -2, 3, 10, -4, 7, 2, -5 };
int max = MaxSum(a);
System.out.println(max);
}

public static int MaxSum(int[] a) {
int out = 0;
int temp = 0;
for (int i = 0; i < a.length; i++) {
temp = temp + a[i];
if (temp > out)
out = temp;
if (temp < 0)
temp= 0;
}
return out;
}

}

 

import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

/**
 * Created by Tony on 2017/3/17.
 */
public class ArrayTest {
  private Array array;
    int sum []={1, -2, 3, 10, -4, 7, 2, -5};
    @Before
    public void setUp() throws Exception {
      array =new Array();
    }

    @Test
    public void testMaxSum() throws Exception {
        assertEquals(18d,array.maxSum(sum),0);
    }
}

 


posted @ 2017-03-17 19:56  hui不去的曾经  阅读(128)  评论(0编辑  收藏  举报