You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

29 lines
926 B

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package class14;
import java.util.TreeSet;
public class Code02_MaxSubArraySumLessOrEqualK {
// 请返回arr中求个子数组的累加和是<=K的并且是最大的。
// 返回这个最大的累加和
public static int getMaxLessOrEqualK(int[] arr, int K) {
// 记录i之前的前缀和按照有序表组织
TreeSet<Integer> set = new TreeSet<Integer>();
// 一个数也没有的时候就已经有一个前缀和是0了
set.add(0);
int max = Integer.MIN_VALUE;
int sum = 0;
// 每一步的i都求子数组必须以i结尾的情况下求个子数组的累加和是<=K的并且是最大的
for (int i = 0; i < arr.length; i++) {
sum += arr[i]; // sum -> arr[0..i];
if (set.ceiling(sum - K) != null) {
max = Math.max(max, sum - set.ceiling(sum - K));
}
set.add(sum); // 当前的前缀和加入到set中去
}
return max;
}
}