|
| 1 | +/** |
| 2 | + * 1982. Find Array Given Subset Sums |
| 3 | + * https://leetcode.com/problems/find-array-given-subset-sums/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given an integer n representing the length of an unknown array that you are trying |
| 7 | + * to recover. You are also given an array sums containing the values of all 2n subset sums of |
| 8 | + * the unknown array (in no particular order). |
| 9 | + * |
| 10 | + * Return the array ans of length n representing the unknown array. If multiple answers exist, |
| 11 | + * return any of them. |
| 12 | + * |
| 13 | + * An array sub is a subset of an array arr if sub can be obtained from arr by deleting some |
| 14 | + * (possibly zero or all) elements of arr. The sum of the elements in sub is one possible |
| 15 | + * subset sum of arr. The sum of an empty array is considered to be 0. |
| 16 | + * |
| 17 | + * Note: Test cases are generated such that there will always be at least one correct answer. |
| 18 | + */ |
| 19 | + |
| 20 | +/** |
| 21 | +* @param {number} n |
| 22 | +* @param {number[]} sums |
| 23 | +* @return {number[]} |
| 24 | +*/ |
| 25 | +var recoverArray = function(n, sums) { |
| 26 | + sums.sort((a, b) => a - b); |
| 27 | + |
| 28 | + const result = []; |
| 29 | + while (result.length < n) { |
| 30 | + const diff = sums[1] - sums[0]; |
| 31 | + |
| 32 | + const withNum = []; |
| 33 | + const withoutNum = []; |
| 34 | + const freq = new Map(); |
| 35 | + for (const sum of sums) { |
| 36 | + freq.set(sum, (freq.get(sum) || 0) + 1); |
| 37 | + } |
| 38 | + |
| 39 | + for (const sum of sums) { |
| 40 | + if (freq.get(sum) > 0) { |
| 41 | + freq.set(sum, freq.get(sum) - 1); |
| 42 | + |
| 43 | + if (freq.get(sum + diff) > 0) { |
| 44 | + freq.set(sum + diff, freq.get(sum + diff) - 1); |
| 45 | + withoutNum.push(sum); |
| 46 | + withNum.push(sum + diff); |
| 47 | + } else { |
| 48 | + return []; |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + if (withoutNum.includes(0)) { |
| 54 | + result.push(diff); |
| 55 | + sums = withoutNum; |
| 56 | + } else { |
| 57 | + result.push(-diff); |
| 58 | + sums = withNum; |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + return result; |
| 63 | +}; |
0 commit comments