DSA Heaps

Construct Target Array with Multiple Sums

Reverse-engineer the build from target back to all-ones using a max-heap and modular replacement.

Hard
Time O(n log n log max) Space O(n)
LeetCode
6 min read
heaps greedy math

Problem#

Start with an array of n ones. In one step, replace any element with the sum of all elements. Given a target, return true iff target is reachable.

Examples#

  • target = [9, 3, 5]true
  • target = [1, 1, 1, 2]false

Constraints#

  • n <= 5 * 10^4, target[i] <= 10^9.

Hints#

Hint 1
Work backwards: the largest entry must have been the most-recently replaced; its predecessor = largest - sum(others) = largest mod sum(others).

Approach#

Reverse the process. Max-heap. Each step: pop the max m; let rest = totalSum - m. The predecessor was m - rest (or m mod rest to fast-forward many consecutive replacements of the same slot). Push it back. Stop when max is 1 or invalid.

Solution#

Construct Target Array with Multiple Sums
class Solution {
public:
bool isPossible(vector<int>& target) {
long long sum = 0;
priority_queue<long long> pq;
for (int x : target) { pq.push(x); sum += x; }
while (pq.top() != 1) {
long long m = pq.top(); pq.pop();
long long rest = sum - m;
if (rest <= 0 || rest >= m) return false;
long long prev = m % rest;
if (prev == 0) prev = rest; // can't be zero
if (prev == m) return false;
sum = sum - m + prev;
pq.push(prev);
}
return true;
}
};

Editorial#

The modulo m % rest is the speedup: if the same slot was the max for many consecutive operations, the predecessor sequence is m, m - rest, m - 2*rest, ... until it drops below rest. That terminal value is exactly m % rest. The prev == 0 guard handles the special case rest = 1 where the slot’s true predecessor is 1.

Complexity#

  • Time: O(n log n log max).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.