|
| 1 | +/** |
| 2 | + * 851. Loud and Rich |
| 3 | + * https://leetcode.com/problems/loud-and-rich/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * There is a group of n people labeled from 0 to n - 1 where each person has a different amount |
| 7 | + * of money and a different level of quietness. |
| 8 | + * |
| 9 | + * You are given an array richer where richer[i] = [ai, bi] indicates that ai has more money than |
| 10 | + * bi and an integer array quiet where quiet[i] is the quietness of the ith person. All the given |
| 11 | + * data in richer are logically correct (i.e., the data will not lead you to a situation where x |
| 12 | + * is richer than y and y is richer than x at the same time). |
| 13 | + * |
| 14 | + * Return an integer array answer where answer[x] = y if y is the least quiet person (that is, |
| 15 | + * the person y with the smallest value of quiet[y]) among all people who definitely have equal |
| 16 | + * to or more money than the person x. |
| 17 | + */ |
| 18 | + |
| 19 | +/** |
| 20 | + * @param {number[][]} richer |
| 21 | + * @param {number[]} quiet |
| 22 | + * @return {number[]} |
| 23 | + */ |
| 24 | +var loudAndRich = function(richer, quiet) { |
| 25 | + const graph = new Array(quiet.length).fill().map(() => []); |
| 26 | + const result = new Array(quiet.length).fill(-1); |
| 27 | + |
| 28 | + for (const [a, b] of richer) { |
| 29 | + graph[b].push(a); |
| 30 | + } |
| 31 | + |
| 32 | + function dfs(person) { |
| 33 | + if (result[person] !== -1) return result[person]; |
| 34 | + |
| 35 | + let quietestPerson = person; |
| 36 | + |
| 37 | + for (const richerPerson of graph[person]) { |
| 38 | + const candidate = dfs(richerPerson); |
| 39 | + if (quiet[candidate] < quiet[quietestPerson]) { |
| 40 | + quietestPerson = candidate; |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + result[person] = quietestPerson; |
| 45 | + return quietestPerson; |
| 46 | + } |
| 47 | + |
| 48 | + for (let i = 0; i < quiet.length; i++) { |
| 49 | + dfs(i); |
| 50 | + } |
| 51 | + |
| 52 | + return result; |
| 53 | +}; |
0 commit comments