给定一个数组arr,返回子数组的最大累加和
例如,arr = [1, -2, 3, 5, -2, 6, -1],所有子数组中,[3, 5, -2, 6]可以累加出最大的和12,所以返回12.
[要求]
时间复杂度为
,空间复杂度为
第一行一个整数N。表示数组长度
接下来一行N个整数表示数组内的元素
输出一个整数表示答案
7 1 -2 3 5 -2 6 -1
12
public static void test(int[] data) {
int max_sum = 0;// 最大值
int count = 0;// 累加和初始化
for (int i = 0; i < data.length; i++) {
if (data[i] + count > 0) {
count += data[i];
max_sum = Math.max(max_sum, count);//每次累加都更新最大值
} else {
count = 0;
}
System.out.println(max_sum);
}
} import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
int max = Integer.MIN_VALUE;
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
max = Math.max(sum, max);
if (sum < 0) {
sum = 0;
}
}
System.out.println(max);
}
}