一维数组及子数组最大和问题,比如数组int[] source = new int[]{1,-2,3,4,6}的子数组的组合最大和是3,4,6的组合13,其他的组合都比这个小;
刚开始是用一种暴力的算法,但是这种算法时间复杂度很高O(n3);就是每个组合的值都算一遍,然后找到最大的;
第二种算法我忘记了,之后补上;
第三种算法的思想是,如果以i为结尾的数组组合的最大值为负数,那么后面的组合值就没有必要加上之前的数组了;
package design;
public class TheMaxOfArray {
/**
* @param source
* 数组
* @param i
* 开始节点
* @param j
* 结束节点
* @return 开始节点至结束节点的和
* @throws Exception
*/
public static int getSumFromArray(int source[], int i, int j)
throws Exception {
if (source == null) {
throw new RuntimeException("输入数组为空!");
}
if (source.length == 0) {
throw new Exception("输入的数组没有内容让我怎么算啊?");
}
if (i > j) {
throw new Exception("数组开始节点比结束节点大!");
}
if (i > source.length || j > source.length) {
throw new Exception("数组越界!");
}
int result = 0;
for (int n = i; n <= j; n++) {
result += source[n];
}
return result;
}
/**
* @param source
* @return 第一种解法,时间复杂度O(n3)
* @throws Exception
*/
public static int findMaxFirst(int source[]) throws Exception {
if (source == null) {
throw new RuntimeException("输入数组为空!");
}
if (source.length == 0) {
throw new Exception("输入的数组没有内容让我怎么算啊?");
}
int max = source[0];
int length = source.length;
/** 暴力解法,i是开始节点,j是结束节点 */
for (int i = 0; i < length; i++) {
for (int j = i; j < length; j++) {
int tempResult = getSumFromArray(source, i, j);
max = max > tempResult ? max : tempResult;
}
}
return max;
}
/**
* @param source
* @return O(n)时间复杂度的算法
* @throws Exception
*/
public static int findMaxFinal(int source[]) throws Exception {
if (source == null) {
throw new RuntimeException("输入数组为空!");
}
if (source.length == 0) {
throw new Exception("输入的数组没有内容让我怎么算啊?");
}
/**
* 设置Max为最大数值,temp为每次以source[i]为结尾的数组的最大值,如果temp为负,则之后的组合不必加上temp,如果为正,
* 则之后的数组组合需要加上temp 这种算法的时间复杂度是O(n),空间复杂度是O(1);
*/
int max = source[0];
int temp = max;
int length = source.length;
for (int i = 1; i < length; i++) {
if (temp > 0) {
temp += source[i];
} else {
temp = source[i];
}
max = max > temp ? max : temp;
}
return max;
}
public static void main(String args[]) throws Exception {
int[] testSource = new int[] { 1, -2, 5, -3, 10 };
System.out.println(findMaxFirst(testSource));
System.out.println(findMaxFinal(testSource));
}
}