|
| 1 | +/** |
| 2 | + * 1601. Maximum Number of Achievable Transfer Requests |
| 3 | + * https://leetcode.com/problems/maximum-number-of-achievable-transfer-requests/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * We have n buildings numbered from 0 to n - 1. Each building has a number of employees. |
| 7 | + * It's transfer season, and some employees want to change the building they reside in. |
| 8 | + * |
| 9 | + * You are given an array requests where requests[i] = [fromi, toi] represents an employee's |
| 10 | + * request to transfer from building fromi to building toi. |
| 11 | + * |
| 12 | + * All buildings are full, so a list of requests is achievable only if for each building, the |
| 13 | + * net change in employee transfers is zero. This means the number of employees leaving is |
| 14 | + * equal to the number of employees moving in. For example if n = 3 and two employees are |
| 15 | + * leaving building 0, one is leaving building 1, and one is leaving building 2, there should |
| 16 | + * be two employees moving to building 0, one employee moving to building 1, and one employee |
| 17 | + * moving to building 2. |
| 18 | + * |
| 19 | + * Return the maximum number of achievable requests. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {number} n |
| 24 | + * @param {number[][]} requests |
| 25 | + * @return {number} |
| 26 | + */ |
| 27 | +var maximumRequests = function(n, requests) { |
| 28 | + let maxAchievable = 0; |
| 29 | + tryCombination(0, 0, new Array(n).fill(0)); |
| 30 | + return maxAchievable; |
| 31 | + |
| 32 | + function tryCombination(index, count, balance) { |
| 33 | + if (index === requests.length) { |
| 34 | + if (balance.every(val => val === 0)) { |
| 35 | + maxAchievable = Math.max(maxAchievable, count); |
| 36 | + } |
| 37 | + return; |
| 38 | + } |
| 39 | + |
| 40 | + const [from, to] = requests[index]; |
| 41 | + balance[from]--; |
| 42 | + balance[to]++; |
| 43 | + tryCombination(index + 1, count + 1, balance); |
| 44 | + balance[from]++; |
| 45 | + balance[to]--; |
| 46 | + |
| 47 | + tryCombination(index + 1, count, balance); |
| 48 | + } |
| 49 | +}; |
0 commit comments