给定一个数组arr,返回子数组的最大累加和
解题思路】cur累加成为负数清零重新累加,max记录cur的最大值
public class MaxSum {
public static int maxSum(int[] arr) {
int max = Integer.MIN_VALUE;
int cur = 0;
for (int i = 0; i < arr.length; i++) {
cur = cur + arr[i];
max = Math.max(max, cur);
if (cur < 0) {
cur = 0;
}
}
return max;
}
public static void main(String[] args) {
int[] arr1= {3, -5, 3, -1, 2, 2, 3};
int maxSum1 = maxSum(arr1);
int[] arr2 = {-3, -2, -5, -1, -4};
int maxSum2 = maxSum(arr2);
}
}