In this post, we are going to discuss leetcode 1292 — Maximum Side Length of a Square with Sum Less than or Equal to Threshold, which is asked in Google, and Amazon interviews.
Problem Analysis
Given a
m x n
matrixmat
and an integerthreshold
, return the maximum side-length of a square with a sum less than or equal tothreshold
or return0
if there is no such square.
Example 1:
Input: mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4
Output: 2
Explanation: The maximum side length of square with sum less than 4 is 2 as shown.
Example 2:
Input: mat = [[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2]], threshold = 1
Output: 0
This is a matrix question, where we need to maintain a memory map.
My Thinking Process
This is a standard matrix problem, where we only need to get the sum of values in a square. Usually for this type of questions, we need to keep a memory map.
The common logic to solve this type of question is:
- Build and maintain a memory map in a matrix
memo
, wherememo[i][j]
would be the sum of all the values from the rectangle0,0
toi,j
from the given matrix. - Loop through the memory map, and assume we are at position
r,c
. We can simply get the sum of values of sizek
…