From 6eb2f1ca93226934e645f64cd5ce11567f331929 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=97=BC=ED=98=9C=EC=A0=95?= <122238744+cyzlcyzl@users.noreply.github.com> Date: Sat, 5 Sep 2026 23:52:12 +0900 Subject: [PATCH] Create 851. Loud and Rich.java --- .../851. Loud and Rich.java" | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 "leetcode3/\354\227\274\355\230\234\354\240\225/851. Loud and Rich.java" diff --git "a/leetcode3/\354\227\274\355\230\234\354\240\225/851. Loud and Rich.java" "b/leetcode3/\354\227\274\355\230\234\354\240\225/851. Loud and Rich.java" new file mode 100644 index 00000000..422401fa --- /dev/null +++ "b/leetcode3/\354\227\274\355\230\234\354\240\225/851. Loud and Rich.java" @@ -0,0 +1,39 @@ +class Solution { + public int[] loudAndRich(int[][] richer, int[] quiet) { + int n = quiet.length; + List> graph = new ArrayList<>(); + for (int i = 0; i < n; i++) { + graph.add(new ArrayList<>()); + } + // richer[i] = [a, b] : a는 b보다 부자 -> b는 a에게 정보를 받을 수 있음 + for (int[] r : richer) { + graph.get(r[1]).add(r[0]); + } + + int[] answer = new int[n]; + Arrays.fill(answer, -1); + + for (int i = 0; i < n; i++) { + dfs(i, graph, quiet, answer); + } + + return answer; + } + + private int dfs(int person, List> graph, int[] quiet, int[] answer) { + if (answer[person] != -1) { + return answer[person]; + } + + answer[person] = person; // 자기 자신이 일단 후보 + + for (int richerPerson : graph.get(person)) { + int candidate = dfs(richerPerson, graph, quiet, answer); + if (quiet[candidate] < quiet[answer[person]]) { + answer[person] = candidate; + } + } + + return answer[person]; + } +}