首页 > 代码库 > 求数组最大子数组和

求数组最大子数组和

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);
    }
}

技术分享

 

求数组最大子数组和