|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.TreeSet; |
| 4 | + |
| 5 | +/** |
| 6 | + * 363. Max Sum of Rectangle No Larger Than K |
| 7 | + * |
| 8 | + * Given a non-empty 2D matrix matrix and an integer k, |
| 9 | + * find the max sum of a rectangle in the matrix such that its sum is no larger than k. |
| 10 | +
|
| 11 | + Example: |
| 12 | + Given matrix = [ |
| 13 | + [1, 0, 1], |
| 14 | + [0, -2, 3] |
| 15 | + ] |
| 16 | + k = 2 |
| 17 | + The answer is 2. Because the sum of rectangle [[0, 1], [-2, 3]] is 2 and 2 is the max number no larger than k (k = 2). |
| 18 | +
|
| 19 | + Note: |
| 20 | + The rectangle inside the matrix must have an area > 0. |
| 21 | + What if the number of rows is much larger than the number of columns? |
| 22 | + */ |
| 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) return 0; |
| 28 | + int col = matrix[0].length; |
| 29 | + int m = Math.min(row, col); |
| 30 | + int n = Math.max(row, col); |
| 31 | + //indicating sum up in every row or every column |
| 32 | + boolean colIsBig = col > row; |
| 33 | + int res = Integer.MIN_VALUE; |
| 34 | + for (int i = 0; i < m; i++) { |
| 35 | + int[] array = new int[n]; |
| 36 | + // sum from row j to row i |
| 37 | + for (int j = i; j >= 0; j--) { |
| 38 | + int val = 0; |
| 39 | + TreeSet<Integer> set = new TreeSet<>(); |
| 40 | + set.add(0); |
| 41 | + //traverse every column/row and sum up |
| 42 | + for (int p = 0; p < n; p++) { |
| 43 | + array[p] = array[p] + (colIsBig ? matrix[j][p] : matrix[p][j]); |
| 44 | + val = val + array[p]; |
| 45 | + //use TreeMap to binary search previous sum to get possible result |
| 46 | + Integer subres = set.ceiling(val - k); |
| 47 | + if (null != subres) { |
| 48 | + res = Math.max(res, val - subres); |
| 49 | + } |
| 50 | + set.add(val); |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + return res; |
| 55 | + } |
| 56 | +} |
0 commit comments