aboutsummaryrefslogtreecommitdiff
path: root/max_side_length_square.c
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2025-01-04 23:04:08 +0100
committerJack Sangdahl <[email protected]>2025-01-04 23:04:08 +0100
commit2a8a768249be900c9946204b45519ebacbb9b485 (patch)
tree405f6323a08df6d0055fcec779c28b305e2803c6 /max_side_length_square.c
parentb5f958e92ce7384d273271d8c594c4bb45a8c6fe (diff)
downloadleetcode-2a8a768249be900c9946204b45519ebacbb9b485.tar.gz
leetcode-2a8a768249be900c9946204b45519ebacbb9b485.zip
1292. maximum side length of a square with sum less than or equal to threshold
Diffstat (limited to 'max_side_length_square.c')
-rw-r--r--max_side_length_square.c53
1 files changed, 53 insertions, 0 deletions
diff --git a/max_side_length_square.c b/max_side_length_square.c
new file mode 100644
index 0000000..5c6e701
--- /dev/null
+++ b/max_side_length_square.c
@@ -0,0 +1,53 @@
+// 1292. Maximum Side Length of a Square with Sum Less than or Equal to
+// Threshold
+#include "leetcode.h"
+
+/*
+ * given a 'm x n' matrix 'mat' and an integer 'threshold', return the maximum
+ * side-length of a square with a sum less than or equal to 'threshold' or
+ * return 0 if there is no such square.
+ */
+
+int maxSideLength(int **mat, int matSize, int *matColSize, int threshold) {
+ int w = matSize, h = matColSize[0], prefix[w][h];
+ for (int x = 0; x < w; x++)
+ for (int y = 0; y < h; y++)
+ prefix[x][y] = mat[x][y] + (x ? prefix[x - 1][y] : 0) +
+ (y ? prefix[x][y - 1] : 0) -
+ (x && y ? prefix[x - 1][y - 1] : 0);
+ int max = w > h ? w : h, best = -1;
+ for (int s = 0; s < max; s++) {
+ for (int x = 0; x < w - s; x++) {
+ for (int y = 0; y < h - s; y++) {
+ int sum = prefix[x + s][y + s] - (x ? prefix[x - 1][y + s] : 0) -
+ (y ? prefix[x + s][y - 1] : 0) +
+ (x && y ? prefix[x - 1][y - 1] : 0);
+ if (sum <= threshold) {
+ best = s;
+ break;
+ }
+ }
+ if (best == s)
+ break;
+ }
+ if (best != s)
+ break;
+ }
+ return best + 1;
+}
+
+int main() {
+ int m1i[3][7] = {
+ {1, 1, 3, 2, 4, 3, 2}, {1, 1, 3, 2, 4, 3, 2}, {1, 1, 3, 2, 4, 3, 2}};
+ int m2i[4][5] = {
+ {2, 2, 2, 2, 2}, {2, 2, 2, 2, 2}, {2, 2, 2, 2, 2}, {2, 2, 2, 2, 2}};
+ struct two_d_arr m1, m2;
+ two_d_arr_init(&m1, 3, 7, m1i);
+ two_d_arr_init(&m2, 4, 5, m2i);
+ printf("%d\n",
+ maxSideLength(m1.arr, m1.row_size, m1.col_size, 4)); // expect: 2
+ printf("%d\n",
+ maxSideLength(m2.arr, m2.row_size, m2.col_size, 1)); // expect: 0
+ two_d_arr_free(&m1);
+ two_d_arr_free(&m2);
+}