Skip to the code
cf.
+50 XP

#54 Largest Square Under Budget

hard

A city map tool shows the land price of each block in grid (all prices are 0 or more). A developer wants the biggest square of blocks whose total price is at most limit.

Write largestSquare(grid, limit) that returns the side length of the largest such square, or 0 if even a single block costs more than limit.

Example 1

Input: grid = [[2,1,3],[1,1,1],[4,1,2]], limit = 5
Output: 2

The top-left 2 by 2 square costs 2 + 1 + 1 + 1 = 5. The full 3 by 3 square costs 16.

Example 2

Input: grid = [[9,9],[9,9]], limit = 8
Output: 0

Every block alone already costs more than 8.

Constraints

  • 1 <= rows, cols <= 300
  • 0 <= grid[r][c] <= 10^4
  • 0 <= limit <= 10^9
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).