forked from algorithm009-class01/algorithm009-class01
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxSumSubmatrix.java
More file actions
38 lines (34 loc) · 1.19 KB
/
MaxSumSubmatrix.java
File metadata and controls
38 lines (34 loc) · 1.19 KB
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
package dynamic;
import java.util.TreeSet;
public class MaxSumSubmatrix {
public int maxSumSubmatrix(int[][] matrix,int k){
if (matrix.length == 0) return 0;
int m = matrix.length,n = matrix[0].length;
int result = Integer.MIN_VALUE;
for (int left = 0;left <n;left++){
int[] sums = new int[m];
for (int right = left;right < n;right++){
for (int i = 0; i < m; i++) {
sums[i] += matrix[i][right];
}
TreeSet<Integer> set = new TreeSet<>();
set.add(0);
int curSum = 0;
for (int sum : sums){
curSum += sum;
Integer num = set.ceiling(curSum-k);
if (num != null ) result = Math.max(result,curSum - num);
set.add(curSum);
}
}
}
return result;
}
public static void main(String[] args) {
int[][] matrix ={{1,0,1},{0,-2,3}};
int k = 2;
MaxSumSubmatrix maxSumSubmatrix = new MaxSumSubmatrix();
int r = maxSumSubmatrix.maxSumSubmatrix(matrix,k);
System.out.println(r);
}
}