KatInterview

363. Max Sum of Rectangle No Larger Than K

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method: 2D to 1D Reduction with Binary Search

The problem asks for the maximum sum of a rectangular submatrix that does not exceed a given value k. A naive approach of checking every possible rectangle would be too slow, with a complexity around O(m^2 * n^2).

Solution

Max Sum of Rectangle No Larger Than K in Python

import bisect

class Solution:
    def maxSumSubmatrix(self, matrix: list[list[int]], k: int) -> int:
        m, n = len(matrix), len(matrix[0])
        ans = -float('inf')

        # To optimize, iterate over the smaller dimension.
        # If rows > cols, iterate through column pairs. Otherwise, row pairs.
        if m > n:
            # n is the smaller dimension
            for c1 in range(n):
                row_sums = [0] * m
                for c2 in range(c1, n):
                    for r in range(m):
                        row_sums[r] += matrix[r][c2]
                    
                    # Solve 1D problem on row_sums
                    ans = max(ans, self.find_max_sum_subarray(row_sums, k))
                    if ans == k: return k
        else:
            # m is the smaller or equal dimension
            for r1 in range(m):
                col_sums = [0] * n
                for r2 in range(r1, m):
                    for c in range(n):
                        col_sums[c] += matrix[r2][c]

                    # Solve 1D problem on col_sums
                    ans = max(ans, self.find_max_sum_subarray(col_sums, k))
                    if ans == k: return k
        
        return ans

    def find_max_sum_subarray(self, arr: list[int], k: int) -> int:
        max_sum = -float('inf')
        prefix_sum = 0
        sorted_prefixes = [0]

        for num in arr:
            prefix_sum += num
            # We want to find a `prev_sum` such that `prefix_sum - prev_sum <= k`
            # This is equivalent to `prev_sum >= prefix_sum - k`.
            # bisect_left finds an insertion point for `target` to maintain sorted order.
            target = prefix_sum - k
            idx = bisect.bisect_left(sorted_prefixes, target)
            
            if idx < len(sorted_prefixes):
                max_sum = max(max_sum, prefix_sum - sorted_prefixes[idx])
            
            # Insert current prefix_sum into the sorted list.
            # insort is O(N), making this 1D solver O(N^2) in total.
            bisect.insort(sorted_prefixes, prefix_sum)
        
        return max_sum

Max Sum of Rectangle No Larger Than K in Java

class Solution {
    public int maxSumSubmatrix(int[][] matrix, int k) {
        int m = matrix.length;
        int n = matrix[0].length;
        int result = Integer.MIN_VALUE;

        // To optimize, iterate over the smaller dimension.
        // Let's ensure n is always the smaller dimension.
        boolean rowIsSmaller = m < n;

        int rows = rowIsSmaller ? n : m;
        int cols = rowIsSmaller ? m : n;

        for (int i = 0; i < cols; i++) {
            // sum_arr stores sums for each element of the larger dimension.
            int[] sumArr = new int[rows];
            for (int j = i; j < cols; j++) {
                for (int l = 0; l < rows; l++) {
                    if (rowIsSmaller) {
                        sumArr[l] += matrix[j][l]; // j is row, l is col
                    } else {
                        sumArr[l] += matrix[l][j]; // l is row, j is col
                    }
                }

                // Solve 1D problem: find max subarray sum <= k.
                result = Math.max(result, findMaxSumSubarray(sumArr, k));

                // Optimization: if we find k, it's the best possible answer.
                if (result == k) {
                    return k;
                }
            }
        }
        return result;
    }

    private int findMaxSumSubarray(int[] arr, int k) {
        int maxSum = Integer.MIN_VALUE;
        TreeSet<Integer> sortedPrefixes = new TreeSet<>();
        sortedPrefixes.add(0);
        int currentSum = 0;

        for (int val : arr) {
            currentSum += val;
            // We want to find a `prevSum` such that `currentSum - prevSum <= k`
            // This is equivalent to `prevSum >= currentSum - k`.
            // `ceiling` finds the smallest element >= the given value.
            Integer prevSum = sortedPrefixes.ceiling(currentSum - k);

            if (prevSum != null) {
                maxSum = Math.max(maxSum, currentSum - prevSum);
            }
            sortedPrefixes.add(currentSum);
        }
        return maxSum;
    }
}

Max Sum of Rectangle No Larger Than K in C++

class Solution {
public:
    int maxSumSubmatrix(vector<vector<int>>& matrix, int k) {
        int m = matrix.size();
        int n = matrix[0].size();
        int result = INT_MIN;

        // To optimize, we should iterate over the smaller dimension.
        // If rows > cols, we iterate through column pairs. Otherwise, row pairs.
        bool iterate_cols = (n <= m);

        int dim_outer = iterate_cols ? n : m;
        int dim_inner = iterate_cols ? m : n;

        for (int i = 0; i < dim_outer; ++i) {
            // sum_arr will store sums for each element of the larger dimension.
            vector<int> sum_arr(dim_inner, 0);
            for (int j = i; j < dim_outer; ++j) {
                // Update sum_arr with the new row/column.
                for (int l = 0; l < dim_inner; ++l) {
                    if (iterate_cols) {
                        sum_arr[l] += matrix[l][j]; // Summing rows for fixed columns j
                    } else {
                        sum_arr[l] += matrix[j][l]; // Summing columns for fixed rows j
                    }
                }
                
                // Solve the 1D problem: find max subarray sum <= k.
                // This uses a sorted set of prefix sums.
                set<int> sorted_prefixes;
                sorted_prefixes.insert(0);
                int current_sum = 0;
                for (int val : sum_arr) {
                    current_sum += val;
                    // We want to find a `prev_sum` such that `current_sum - prev_sum <= k`
                    // This is equivalent to `prev_sum >= current_sum - k`.
                    // `lower_bound` finds the first element not less than the target.
                    auto it = sorted_prefixes.lower_bound(current_sum - k);
                    
                    if (it != sorted_prefixes.end()) {
                        result = max(result, current_sum - *it);
                    }
                    sorted_prefixes.insert(current_sum);
                }

                // Optimization: if we find k, it's the best possible answer.
                if (result == k) {
                    return k;
                }
            }
        }
        return result;
    }
};

Max Sum of Rectangle No Larger Than K in TypeScript

function maxSumSubmatrix(matrix: number[][], k: number): number {
    const m = matrix.length;
    const n = matrix[0].length;
    let result = -Infinity;

    const findMaxSumSubarray = (arr: number[]): void => {
        let currentSum = 0;
        const sortedPrefixes: number[] = [0];

        for (const val of arr) {
            currentSum += val;

            // We want to find a `prevSum` such that `currentSum - prevSum <= k`
            // This is equivalent to `prevSum >= currentSum - k`.
            const target = currentSum - k;

            // Binary search to find the insertion point for target.
            // This gives us the index of the first element >= target.
            let left = 0, right = sortedPrefixes.length;
            while (left < right) {
                const mid = Math.floor((left + right) / 2);
                if (sortedPrefixes[mid] < target) {
                    left = mid + 1;
                } else {
                    right = mid;
                }
            }
            const idx = left;

            if (idx < sortedPrefixes.length) {
                result = Math.max(result, currentSum - sortedPrefixes[idx]);
            }

            // Insert currentSum into the sorted array.
            // This is O(N) due to splicing.
            sortedPrefixes.splice(idx, 0, currentSum); // This is not the right way to insert, we need to find insertion point for currentSum
            let insertIdx = 0;
            let insertRight = sortedPrefixes.length;
            while(insertIdx < insertRight) {
                const mid = Math.floor((insertIdx + insertRight) / 2);
                if(sortedPrefixes[mid] < currentSum) {
                    insertIdx = mid + 1;
                } else {
                    insertRight = mid;
                }
            }
            sortedPrefixes.splice(insertIdx, 0, currentSum);
        }
    };

    // Optimize: iterate over the smaller dimension.
    if (m > n) { // n is smaller
        for (let c1 = 0; c1 < n; c1++) {
            const rowSums = new Array(m).fill(0);
            for (let c2 = c1; c2 < n; c2++) {
                for (let r = 0; r < m; r++) {
                    rowSums[r] += matrix[r][c2];
                }
                findMaxSumSubarray(rowSums);
                if (result === k) return k;
            }
        }
    } else { // m is smaller or equal
        for (let r1 = 0; r1 < m; r1++) {
            const colSums = new Array(n).fill(0);
            for (let r2 = r1; r2 < m; r2++) {
                for (let c = 0; c < n; c++) {
                    colSums[c] += matrix[r2][c];
                }
                findMaxSumSubarray(colSums);
                if (result === k) return k;
            }
        }
    }

    return result;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.