Largest rectangle sum smaller than num in JavaScript

We are required to write a JavaScript function that takes in a 2-D array of Numbers as the first argument and a target sum number as the second argument.

Our function should find out that rectangle from the 2-D array which has the greatest sum among all rectangles in the array but just less than or equal to the target sum specified by the second argument to the function.

Problem Statement

Given a 2D matrix and a target number, find the largest rectangle sum that is smaller than or equal to the target. The function should return that largest sum.

For example, if the input to the function is:

const arr = [
    [1, 0, 1],
    [0, -2, 3]
];
const num = 2;

Then the output should be:

2

Output Explanation

The algorithm finds the rectangle with sum 2, which comes from the submatrix:

[
    [0, 1],
    [-2, 3]
]
// Sum: 0 + 1 + (-2) + 3 = 2

Algorithm Approach

This problem uses Kadane's algorithm extended to 2D arrays. The approach involves:

  • Compress rows between every pair of rows
  • Apply modified Kadane's algorithm on the compressed array
  • Track the maximum sum that doesn't exceed the target

Example Implementation

const arr = [
    [1, 0, 1],
    [0, -2, 3]
];
const num = 2;

const maxSum = (arr = [], num = 1) => {
    const rows = arr.length;
    const cols = arr[0].length;
    let maxSum = -Infinity;
    
    for(let l = 0; l < rows; l++) {
        const dp = Array(cols).fill(0);
        
        for(let r = l; r < rows; r++) {
            let sum = 0, max = -Infinity;
            
            for(let c = 0; c < cols; c++) {
                dp[c] += arr[r][c];
                if(sum < 0) sum = 0;
                sum += dp[c];
                max = Math.max(max, sum);
            }
            
            if(max <= num) {
                maxSum = Math.max(max, maxSum);
            } else {
                max = -Infinity;
                for(let c = 0; c < cols; c++) {
                    sum = 0;
                    for(let d = c; d < cols; d++) {
                        sum += dp[d];
                        if(sum <= num) max = Math.max(sum, max);
                    }
                }
                maxSum = Math.max(max, maxSum);
            }
            
            if(maxSum === num) return num;
        }
    }
    return maxSum;
};

console.log(maxSum(arr, num));
2

How It Works

The algorithm works in two phases:

  1. Row Compression: For each pair of rows, compress the matrix into a 1D array by summing columns
  2. Modified Kadane's: Apply Kadane's algorithm with the constraint that the sum must not exceed the target

When the maximum subarray sum exceeds the target, the algorithm falls back to checking all possible subarrays to find the largest valid sum.

Time Complexity

The time complexity is O(rows² × cols²) in the worst case, where we need to check all possible rectangle combinations when the optimal subarray exceeds the target.

Conclusion

This algorithm efficiently finds the largest rectangle sum in a 2D matrix that doesn't exceed a given target. It combines Kadane's algorithm with constraint checking to solve this optimization problem.

Updated on: 2026-03-15T23:19:00+05:30

201 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements