题目描述
给定一个数组arr,返回子数组的最大累加和
例如,arr = [1, -2, 3, 5, -2, 6, -1],所有子数组中,[3, 5, -2, 6]可以累加出最大的和12,所以返回12.
题目保证没有全为负数的数据
[要求]
时间复杂度为O(n)O(n),空间复杂度为O(1)O(1)
分析
利用temp变量保存当前累加的和,如果为负数就为0 ,重新开始计算,考察知识点:分治,动态规划
java代码
public class MaxofSubArray {
public static void main(String[] args) {
int[] a = {1, -2, 3, 5, -2, 6, -1};
System.out.println("Max of subArray: " + solution(a));
}
public static int solution(int[] array) {
int temp = 0;
int max = Integer.MIN_VALUE;
for (int i = 0; i < array.length; i++) {
temp += array[i];
max = Math.max(temp, max);
temp = temp > 0 ? temp : 0;
System.out.println("temp= " + temp+" max = " + max+" temp = " + temp);
}
return max;
}
}
打印结果:
temp= 1 max = 1 temp = 1
temp= 0 max = 1 temp = 0
temp= 3 max = 3 temp = 3
temp= 8 max = 8 temp = 8
temp= 6 max = 8 temp = 6
temp= 12 max = 12 temp = 12
temp= 11 max = 12 temp = 11
Max of subArray: 12