Naive but accepted java solution.


  • 2
    I

    Well, I think that this is the most direct solution for this problem. We just add the numbers in every rectangle and find the sum closest but not larger than k. Since the array is 2-d, we have 4 points to decide the rectangle, the algorithm will be O(n^2).

    public class Solution {
    public int maxSumSubmatrix(int[][] matrix, int k) {
        
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return 0;
        }
        
        int[][] sums = new int[matrix.length][matrix[0].length];
        
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                if (j == 0) {
                    sums[i][j] = matrix[i][j];
                } else {
                    sums[i][j] = sums[i][j - 1] + matrix[i][j];
                }
            }
        }
        
        /* O(n^4) loop */
        int max = 0;
        boolean firstMax = false;
        int tmpSum = 0;
        for (int i = 0; i < matrix[0].length; i++) {
            for (int j = i; j < matrix[0].length; j++) {
                for (int m = 0; m < matrix.length; m++) {
                    tmpSum = 0;
                    for (int n = m; n < matrix.length; n++) {
                        if (i == 0) {
                            tmpSum += sums[n][j];
                        } else {
                            tmpSum += sums[n][j] - sums[n][i - 1];
                        }
                        if (tmpSum > k) {
                            continue;
                        } else {
                            if (firstMax == false) {
                                max = tmpSum;
                                firstMax = true;
                            } else if ((k - tmpSum) < (k - max)) {
                                max = tmpSum;
                            }
                        }
                    }
                }
            }
        }
        return max;
    }
    

    }


  • 6

    Actually we have 2 points to define a rectangle. The algorithm will be O(n^4).


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.