leetcode 1292. 元素和小於等於閾值的正方形的最大邊長
阿新 • • 發佈:2021-06-13
給你一個大小為m x n的矩陣mat和一個整數閾值threshold。
請你返回元素總和小於或等於閾值的正方形區域的最大邊長;如果沒有這樣的正方形區域,則返回 0。
示例 1:
輸入:mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4
輸出:2
解釋:總和小於或等於 4 的正方形的最大邊長為 2,如圖所示。
示例 2:
輸入: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
輸出:0
示例 3:
輸入:mat = [[1,1,1,1],[1,0,0,0],[1,0,0,0],[1,0,0,0]], threshold = 6
輸出:3
示例 4:
輸入:mat = [[18,70],[61,1],[25,85],[14,40],[11,96],[97,96],[63,45]], threshold = 40184
輸出:2
提示:
1 <= m, n <= 300
m == mat.length
n == mat[i].length
0 <= mat[i][j] <= 10000
0 <= threshold<= 10^5
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
public int maxSideLength(int[][] mat, int threshold) { int a = mat.length; int b = mat[0].length; int[][] arr = new int[a + 1][b + 1]; int min = 0; for (int i = 1; i <= a; i++) { for (int j = 1; j <= b; j++) { arr[i][j] = mat[i - 1][j - 1] + arr[i - 1][j] + arr[i][j - 1] - arr[i - 1][j - 1];int st = 0; int end = Math.min(i, j); while (st <= end) { int m = st + ((end - st) >> 1); int sum = arr[i][j] + arr[i - m][j - m] - arr[i - m][j] - arr[i][j - m]; if (sum <= threshold) { st = m + 1; min = Math.max(m, min); } else { end = m - 1; } } } } return min; }