与前面的方法相似,对于处理列和有所变化 这里使用set来记录所有子串的和(从0到所有位置),sum表示当前从0到该位置的和 a + b = sum a是set中记录的值,b是我们所有的值,题目中要求 b <= k 那么 sum - a <= k , a >= sum - k 那么只要找到set中最小的sum-k即可,这就是treeset中的ceiling方法
Integer java.util.TreeSet.ceiling(Integer e) Returns the least element in this set greater than or equal to the given element, or null if there is no such element.
代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//最大且小于k
public int maxSumSubmatrix(int[][] matrix, int k) {
int maxSum = Integer.MIN_VALUE;
int up = 0;
int down = 0;
int right = 0;
int left = 0;
for (int i = 0; i < matrix[0].length; i++) {
int a[] = new int[matrix.length];
for (int j = i; j < matrix[0].length; j++) {
// 填充a
for (int h = 0; h < matrix.length; h++) {
a[h] += matrix[h][j];
}
// 找到最大值
int tmpSum = 0;
TreeSet<Integer> set = new TreeSet<Integer>();
//结果是本身,比如a=[1,2],k=1
set.add(0);
for (Integer integer : a) {
tmpSum += integer;
Integer tmp = set.ceiling(tmpSum - k);
if(tmp != null){
maxSum = Math.max(maxSum, tmpSum - tmp);
}
set.add(tmpSum);
}
}
}
return maxSum;
}
Smallest subarray with sum greater than a given value