|
| 1 | +/** |
| 2 | + * 1583. Count Unhappy Friends |
| 3 | + * https://leetcode.com/problems/count-unhappy-friends/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given a list of preferences for n friends, where n is always even. |
| 7 | + * |
| 8 | + * For each person i, preferences[i] contains a list of friends sorted in the order of preference. |
| 9 | + * In other words, a friend earlier in the list is more preferred than a friend later in the list. |
| 10 | + * Friends in each list are denoted by integers from 0 to n-1. |
| 11 | + * |
| 12 | + * All the friends are divided into pairs. The pairings are given in a list pairs, where |
| 13 | + * pairs[i] = [xi, yi] denotes xi is paired with yi and yi is paired with xi. |
| 14 | + * |
| 15 | + * However, this pairing may cause some of the friends to be unhappy. A friend x is unhappy if x |
| 16 | + * is paired with y and there exists a friend u who is paired with v but: |
| 17 | + * - x prefers u over y, and |
| 18 | + * - u prefers x over v. |
| 19 | + * |
| 20 | + * Return the number of unhappy friends. |
| 21 | + */ |
| 22 | + |
| 23 | +/** |
| 24 | + * @param {number} n |
| 25 | + * @param {number[][]} preferences |
| 26 | + * @param {number[][]} pairs |
| 27 | + * @return {number} |
| 28 | + */ |
| 29 | +var unhappyFriends = function(n, preferences, pairs) { |
| 30 | + const rank = Array.from({ length: n }, () => new Array(n).fill(0)); |
| 31 | + const pairMap = new Array(n).fill(0); |
| 32 | + let result = 0; |
| 33 | + |
| 34 | + for (let i = 0; i < n; i++) { |
| 35 | + for (let j = 0; j < n - 1; j++) { |
| 36 | + rank[i][preferences[i][j]] = j; |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + for (const [x, y] of pairs) { |
| 41 | + pairMap[x] = y; |
| 42 | + pairMap[y] = x; |
| 43 | + } |
| 44 | + |
| 45 | + for (let x = 0; x < n; x++) { |
| 46 | + const y = pairMap[x]; |
| 47 | + for (const u of preferences[x]) { |
| 48 | + if (u === y) break; |
| 49 | + const v = pairMap[u]; |
| 50 | + if (rank[u][x] < rank[u][v]) { |
| 51 | + result++; |
| 52 | + break; |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + return result; |
| 58 | +}; |
0 commit comments