|
| 1 | +/** |
| 2 | + * 1354. Construct Target Array With Multiple Sums |
| 3 | + * https://leetcode.com/problems/construct-target-array-with-multiple-sums/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given an array target of n integers. From a starting array arr consisting of n 1's, |
| 7 | + * you may perform the following procedure: |
| 8 | + * - let x be the sum of all elements currently in your array. |
| 9 | + * - choose index i, such that 0 <= i < n and set the value of arr at index i to x. |
| 10 | + * - You may repeat this procedure as many times as needed. |
| 11 | + * |
| 12 | + * Return true if it is possible to construct the target array from arr, otherwise, return false. |
| 13 | + */ |
| 14 | + |
| 15 | +/** |
| 16 | + * @param {number[]} target |
| 17 | + * @return {boolean} |
| 18 | + */ |
| 19 | +function isPossible(target) { |
| 20 | + let totalSum = target.reduce((sum, num) => sum + num, 0); |
| 21 | + const heap = [...target]; |
| 22 | + |
| 23 | + buildHeap(); |
| 24 | + |
| 25 | + while (heap[0] > 1) { |
| 26 | + const largest = heap[0]; |
| 27 | + totalSum -= largest; |
| 28 | + if (totalSum < 1) return false; |
| 29 | + const newValue = largest - Math.floor((largest - 1) / totalSum) * totalSum; |
| 30 | + if (newValue === largest) return false; |
| 31 | + totalSum += newValue; |
| 32 | + heap[0] = newValue; |
| 33 | + heapifyDown(0); |
| 34 | + } |
| 35 | + |
| 36 | + return true; |
| 37 | + |
| 38 | + function heapifyDown(index) { |
| 39 | + let largest = index; |
| 40 | + const left = 2 * index + 1; |
| 41 | + const right = 2 * index + 2; |
| 42 | + if (left < heap.length && heap[left] > heap[largest]) largest = left; |
| 43 | + if (right < heap.length && heap[right] > heap[largest]) largest = right; |
| 44 | + if (largest !== index) { |
| 45 | + [heap[index], heap[largest]] = [heap[largest], heap[index]]; |
| 46 | + heapifyDown(largest); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + function buildHeap() { |
| 51 | + for (let i = Math.floor(heap.length / 2) - 1; i >= 0; i--) { |
| 52 | + heapifyDown(i); |
| 53 | + } |
| 54 | + } |
| 55 | +} |
0 commit comments