Largest rectangle sum smaller than num in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

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.

The function should then finally 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 −

const output = 2;

Output Explanation:

Because the smallest rectangle is −

[
   [0, 1]
   [-2, 3]
]

Example

The code for this will be −

 Live Demo

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));

Output

And the output in the console will be −

2
raja
Published on 18-Mar-2021 09:07:22
Advertisements