Maximum Side Length of a Square with Sum Less than or Equal to Threshold LeetCode solution in JavaScript
1/**2* @param {number[][]} mat3* @param {number} threshold4* @return {number}5*/6var maxSideLength = function (mat, threshold) {7const n = mat.length,8m = mat[0].length;910// build sum matrix11let sum = [];12for (let i = 0; i <= n; i++) {13sum.push(new Array(m + 1).fill(0));14for (let j = 0; j <= m; j++) {15if (i == 0 || j == 0) {16continue;17}18sum[i][j] =19sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1] + mat[i - 1][j - 1];20}21}2223// function to check square sum <= threshold24const underThreshold = function (len) {25for (let i = len; i <= n; i++) {26for (let j = len; j <= m; j++) {27if (28sum[i][j] -29sum[i - len][j] -30sum[i][j - len] +31sum[i - len][j - len] <=32threshold33) {34return true;35}36}37}38return false;39};4041// binary search42let l = 0,43r = Math.min(n, m);44while (l <= r) {45const mid = Math.floor((l + r) / 2);46if (underThreshold(mid)) {47l = mid + 1;48} else {49r = mid - 1;50}51}52return r;53};