LeetCode 363: Max Sum of Rectangle No Larger Than K Solution

Master LeetCode problem 363 (Max Sum of Rectangle No Larger Than K), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

363. Max Sum of Rectangle No Larger Than K

Problem Explanation

Explanation

To solve this problem, we can use the concept of prefix sum along with binary search. We iterate over all possible pairs of rows and use the prefix sum to calculate the sum of elements between these two rows for each column. This reduces the problem to finding the maximum subarray sum no larger than k in a 1D array. We can maintain a set of prefix sums and use binary search to find the closest sum to k.

Algorithm:

  1. Iterate over all possible pairs of rows.
  2. Calculate the sum of elements between these two rows for each column and store in an array sums.
  3. For each pair of rows, find the maximum subarray sum no larger than k in the sums array using a set to store prefix sums and binary search.
  4. Update the maximum sum found so far.

Time Complexity: O(m^2 * n * log(n)) Space Complexity: O(n)

Solution Code

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

        for (int i = 0; i < m; i++) {
            int[] sums = new int[n];
            for (int j = i; j < m; j++) {
                TreeSet<Integer> set = new TreeSet<>();
                set.add(0);
                int prefixSum = 0;
                for (int l = 0; l < n; l++) {
                    sums[l] += matrix[j][l];
                    prefixSum += sums[l];
                    Integer target = set.ceiling(prefixSum - k);
                    if (target != null) {
                        maxSum = Math.max(maxSum, prefixSum - target);
                    }
                    set.add(prefixSum);
                }
            }
        }

        return maxSum;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 363 (Max Sum of Rectangle No Larger Than K)?

This page provides optimized solutions for LeetCode problem 363 (Max Sum of Rectangle No Larger Than K) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 363 (Max Sum of Rectangle No Larger Than K)?

The time complexity for LeetCode 363 (Max Sum of Rectangle No Larger Than K) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 363 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 363 in Java, C++, or Python.

Back to LeetCode Solutions