From 0f5f8974149788483539f4d4d2aee20da314de85 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Mon, 13 May 2024 17:05:04 +0200 Subject: [PATCH] =?UTF-8?q?java:=20add=20=C2=AB2373.=20Largest=20Local=20V?= =?UTF-8?q?alues=20in=20a=20Matrix=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- java/largest-local-values-in-a-matrix.java | 32 ++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 java/largest-local-values-in-a-matrix.java diff --git a/java/largest-local-values-in-a-matrix.java b/java/largest-local-values-in-a-matrix.java new file mode 100644 index 0000000..19817fe --- /dev/null +++ b/java/largest-local-values-in-a-matrix.java @@ -0,0 +1,32 @@ +class Solution { + private boolean isValid(int n, int y, int x) { + return y >= 0 && y < n && x >= 0 && x < n; + } + + private void addLocal(int[][] grid, int[][] result, int y, int x) { + for (int d = 0; d < 9; ++d) { + int dy = (d / 3) - 1; + int dx = (d % 3) - 1; + + if (!isValid(grid.length - 2, y - 1 + dy, x - 1 + dx)) { + continue; + } + + result[y - 1 + dy][x - 1 + dx] = Math.max(result[y - 1 + dy][x - 1 + dx], grid[y][x]); + } + } + + public int[][] largestLocal(int[][] grid) { + int N = grid.length; + int[][] result = new int[N - 2][N - 2]; + + for (int i = 0; i < N * N; ++i) { + int y = i / N; + int x = i % N; + + addLocal(grid, result, y, x); + } + + return result; + } +}