最大子数组之和,子数组是连续的,数组元素包含正整数、零、负整数(数组全为负作为特殊情况分析)
package csu.algorithm;
import java.util.Arrays;
/**
* 最大子序列
*
* @author wkp
*
*/
public class MaxSub {
/**
* 最简单的直接方法,遍历数组,计算arr[0]开始的最大子序列之和curMax,依次计算以arr[1].....arr[n-1]开头的最大子序列之和
*/
public static int subMax1(int[] arr) {
int subMax = 0;
int curMax = 0;// 记录当前最大子序列之和
for (int i = 0; i < arr.length; i++) {
curMax = 0;
for (int j = i; j < arr.length; j++) {
curMax += arr[j];
if (curMax > subMax) {
subMax = curMax;
}
}
}
return subMax;
}
/**
* 第二种方法,时间复杂度为O(n),并且记录了最大和的数组
*
* @param arr
* @return
*/
public static int subMax2(int[] arr) {
int[] subArr = new int[10];
int maxSum = 0;
int curSum = 0;
int j = 0;
int count = 0;
for (int i = 0; i < arr.length; i++) {
curSum += arr[i];
subArr[j] = arr[i];//记录最大和的子数组
j++;
if (curSum > maxSum) {
maxSum = curSum;
count++; // 交换几次就是最大子序列和中数组元素的个数
}
if (curSum < 0) {
curSum = 0;
j = 0;
}
}
int[] maxSubArr = new int[count];
for (int i = 0; i < count; i++) {
maxSubArr[i] = subArr[i];
}
System.out.println(Arrays.toString(maxSubArr));
System.out.println("子序列最大的和:" + maxSum);
return maxSum;
}
public static void main(String[] args) {
int[] arr = { 2, 4, -7, 3, -4, 5, 2, -1, 2, 6, -4, 8, 3 };
System.out.println(subMax1(arr));
System.out.println(subMax2(arr));
}
}