FastPrepLargest Sub-Grid
Problems/Largest Sub-Grid

Largest Sub-Grid

MathWorks logoMathWorks● MediumFULLTIMEOA
QuestionFunctionExamplesConstraints

Problem statement

Source note: 🐼 Corrected on 2026-07-18. The reported source requires every square subgrid of the chosen size to stay within maxSum. The sample with maxSum = 4 therefore has answer 1. The judged core task matches about 99% of the reported source.

Given a square integer matrix grid and an integer maxSum, find the maximum side length k such that the sum of every k x k square subgrid is at most maxSum.

If no size satisfies this condition, return 0.

Function

largestSubGrid(grid: int[][], maxSum: int) → int

Examples

Example 1

grid = [[2, 2, 2], [3, 3, 3], [4, 4, 4]]maxSum = 4return = 1

Every 1 x 1 square has sum 2, 3, or 4, so size 1 is valid. A 2 x 2 square in the first two rows already has sum 10, so size 2 is invalid. The maximum valid side length is 1.

Constraints

  • grid is an n x n matrix.
  • 1 <= n <= 300
  • 1 <= maxSum <= 10^9

More MathWorks problems

  • Earliest Time to Schedule a MeetingOA · Seen Nov 2026
  • Minimum Cost to Serve Requests on a RingOA · Seen Nov 2026
  • Minimum Tree Diameter After Removing K LeavesOA · Seen Nov 2026
All MathWorks interview questionsSee MathWorks hiring insights
Saved
class Solution {
    public int largestSubGrid(int[][] grid, int maxSum) {
      // write your code here
    }

}
Checking account…