Skip to content

Commit 181b2cd

Browse files
committed
Add solution #851
1 parent 56e89e8 commit 181b2cd

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -658,6 +658,7 @@
658658
848|[Shifting Letters](./0848-shifting-letters.js)|Medium|
659659
849|[Maximize Distance to Closest Person](./0849-maximize-distance-to-closest-person.js)|Medium|
660660
850|[Rectangle Area II](./0850-rectangle-area-ii.js)|Hard|
661+
851|[Loud and Rich](./0851-loud-and-rich.js)|Medium|
661662
867|[Transpose Matrix](./0867-transpose-matrix.js)|Easy|
662663
868|[Binary Gap](./0868-binary-gap.js)|Easy|
663664
872|[Leaf-Similar Trees](./0872-leaf-similar-trees.js)|Easy|

solutions/0851-loud-and-rich.js

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
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

Comments
 (0)