Created
January 18, 2026 18:09
-
-
Save tatsuyax25/33ce959718605a4e62d12914c5bd637b to your computer and use it in GitHub Desktop.
A k x k magic square is a k x k grid filled with integers such that every row sum, every column sum, and both diagonal sums are all equal. The integers in the magic square do not have to be distinct. Every 1 x 1 grid is trivially a magic square. Giv
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * @param {number[][]} grid | |
| * @return {number} | |
| */ | |
| var largestMagicSquare = function(grid) { | |
| const m = grid.length; | |
| const n = grid[0].length; | |
| // Helper: check if the k×k square starting at (r, c) is magic | |
| function isMagic(r, c, k) { | |
| // Compute the target sum using the first row | |
| let target = 0; | |
| for (let j = 0; j < k; j++) { | |
| target += grid[r][c + j]; | |
| } | |
| // Check all row sums | |
| for (let i = 0; i < k; i++) { | |
| let rowSum = 0; | |
| for (let j = 0; j < k; j++) { | |
| rowSum += grid[r + i][c + j]; | |
| } | |
| if (rowSum !== target) return false; | |
| } | |
| // Check all column sums | |
| for (let j = 0; j < k; j++) { | |
| let colSum = 0; | |
| for (let i = 0; i < k; i++) { | |
| colSum += grid[r + i][c + j]; | |
| } | |
| if (colSum !== target) return false; | |
| } | |
| // Check main diagonal | |
| let diag1 = 0; | |
| for (let i = 0; i < k; i++) { | |
| diag1 += grid[r + i][c + i]; | |
| } | |
| if (diag1 !== target) return false; | |
| // Check anti-diagonal | |
| let diag2 = 0; | |
| for (let i = 0; i < k; i++) { | |
| diag2 += grid[r + i][c + (k - 1 - i)]; | |
| } | |
| if (diag2 !== target) return false; | |
| return true; | |
| } | |
| // Try sizes from largest to smallest | |
| const maxK = Math.min(m, n); | |
| for (let k = maxK; k >= 2; k--) { | |
| for (let r = 0; r + k <= m; r++) { | |
| for (let c = 0; c + k <= n; c++) { | |
| if (isMagic(r, c, k)) { | |
| return k; // first valid k is the largest | |
| } | |
| } | |
| } | |
| } | |
| // If no k > 1 works, return 1 | |
| return 1; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment