|
21 | 21 | What if the number of rows is much larger than the number of columns?
|
22 | 22 | */
|
23 | 23 | public class _363 {
|
24 |
| - /**reference: https://discuss.leetcode.com/topic/48854/java-binary-search-solution-time-complexity-min-m-n-2-max-m-n-log-max-m-n*/ |
25 |
| - public int maxSumSubmatrix(int[][] matrix, int k) { |
26 |
| - int row = matrix.length; |
27 |
| - if (row == 0) { |
28 |
| - return 0; |
29 |
| - } |
30 |
| - int col = matrix[0].length; |
31 |
| - int m = Math.min(row, col); |
32 |
| - int n = Math.max(row, col); |
33 |
| - //indicating sum up in every row or every column |
34 |
| - boolean colIsBig = col > row; |
35 |
| - int res = Integer.MIN_VALUE; |
36 |
| - for (int i = 0; i < m; i++) { |
37 |
| - int[] array = new int[n]; |
38 |
| - // sum from row j to row i |
39 |
| - for (int j = i; j >= 0; j--) { |
40 |
| - int val = 0; |
41 |
| - TreeSet<Integer> set = new TreeSet<>(); |
42 |
| - set.add(0); |
43 |
| - //traverse every column/row and sum up |
44 |
| - for (int p = 0; p < n; p++) { |
45 |
| - array[p] = array[p] + (colIsBig ? matrix[j][p] : matrix[p][j]); |
46 |
| - val = val + array[p]; |
47 |
| - //use TreeMap to binary search previous sum to get possible result |
48 |
| - Integer subres = set.ceiling(val - k); |
49 |
| - if (null != subres) { |
50 |
| - res = Math.max(res, val - subres); |
| 24 | + public static class Solution1 { |
| 25 | + /** reference: https://discuss.leetcode.com/topic/48854/java-binary-search-solution-time-complexity-min-m-n-2-max-m-n-log-max-m-n */ |
| 26 | + public int maxSumSubmatrix(int[][] matrix, int k) { |
| 27 | + int row = matrix.length; |
| 28 | + if (row == 0) { |
| 29 | + return 0; |
| 30 | + } |
| 31 | + int col = matrix[0].length; |
| 32 | + int m = Math.min(row, col); |
| 33 | + int n = Math.max(row, col); |
| 34 | + //indicating sum up in every row or every column |
| 35 | + boolean colIsBig = col > row; |
| 36 | + int res = Integer.MIN_VALUE; |
| 37 | + for (int i = 0; i < m; i++) { |
| 38 | + int[] array = new int[n]; |
| 39 | + // sum from row j to row i |
| 40 | + for (int j = i; j >= 0; j--) { |
| 41 | + int val = 0; |
| 42 | + TreeSet<Integer> set = new TreeSet<>(); |
| 43 | + set.add(0); |
| 44 | + //traverse every column/row and sum up |
| 45 | + for (int p = 0; p < n; p++) { |
| 46 | + array[p] = array[p] + (colIsBig ? matrix[j][p] : matrix[p][j]); |
| 47 | + val = val + array[p]; |
| 48 | + //use TreeMap to binary search previous sum to get possible result |
| 49 | + Integer subres = set.ceiling(val - k); |
| 50 | + if (null != subres) { |
| 51 | + res = Math.max(res, val - subres); |
| 52 | + } |
| 53 | + set.add(val); |
51 | 54 | }
|
52 |
| - set.add(val); |
53 | 55 | }
|
54 | 56 | }
|
| 57 | + return res; |
55 | 58 | }
|
56 |
| - return res; |
57 | 59 | }
|
58 | 60 | }
|
0 commit comments