Code41 离K最近的子数组累加和

226 阅读1分钟

题目描述

  • 给定一个数组arr,在给定一个K值
  • 返回累加和小于等于K,但是离K最近的子数组累加和

思路

  • 累加每一个位置结尾的累加和, 寻找之前最接近 sum - K 的累加和
  • 举例:
  • 求累加和最接近20的 sum[0..i] = 100
  • 那么只要在 arr[0...i-1] 上寻找sum最接近100-20 = 80的,假设找到的累加和是j
  • 那就返回 sum - j (每个位置如此 求max, 从左到右的模型)

code

public class Code41 {

    public static int nearestKSum(int[] arr, int K) {
        if (arr == null || arr.length <= 0) {
            return 0;
        }
        TreeSet<Integer> treeSet = new TreeSet<>();
        int sum = 0;
        int max = Integer.MIN_VALUE;
        // 一个数也没有的时候,就已经有一个前缀和是0了
        treeSet.add(0);
        for (int i = 0; i < arr.length; i++) {
            sum += arr[i];
            if (treeSet.ceiling(sum - K) != null) {
                max = Math.max(sum - treeSet.ceiling(sum - K), max);
            }
            treeSet.add(sum);
        }
        return max;
    }
}