Skip to content

1354. Construct Target Array With Multiple Sums 👍

  • Time: $O(n + \log(\Sigma |\texttt{target[i]}|) \cdot \log n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
 public:
  bool isPossible(vector<int>& target) {
    if (target.size() == 1)
      return target[0] == 1;

    long sum = accumulate(target.begin(), target.end(), 0L);
    priority_queue<int> maxHeap;

    for (const int num : target)
      maxHeap.push(num);

    while (maxHeap.top() > 1) {
      const long mx = maxHeap.top();
      maxHeap.pop();
      const long restSum = sum - mx;
      // Only occurs if n == 2.
      if (restSum == 1)
        return true;
      const long updated = mx % restSum;
      // updated == 0 (invalid) or didn't change.
      if (updated == 0 || updated == mx)
        return false;
      maxHeap.push(updated);
      sum = sum - mx + updated;
    }

    return true;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
  public boolean isPossible(int[] target) {
    if (target.length == 1)
      return target[0] == 1;

    long sum = Arrays.stream(target).asLongStream().sum();
    Queue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());

    for (final int num : target)
      maxHeap.offer(num);

    while (maxHeap.peek() > 1) {
      final long mx = maxHeap.poll();
      final long restSum = sum - mx;
      // Only occurs if n == 2.
      if (restSum == 1)
        return true;
      final long updated = mx % restSum;
      // updated == 0 (invalid) or didn't change.
      if (updated == 0 || updated == mx)
        return false;
      maxHeap.offer((int) updated);
      sum = sum - mx + updated;
    }

    return true;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:
  def isPossible(self, target: list[int]) -> bool:
    if len(target) == 1:
      return target[0] == 1

    summ = sum(target)
    maxHeap = [-num for num in target]
    heapq.heapify(maxHeap)

    while -maxHeap[0] > 1:
      mx = -heapq.heappop(maxHeap)
      restSum = summ - mx
      # Only occurs if n == 2.
      if restSum == 1:
        return True
      updated = mx % restSum
      # updated == 0 (invalid) or didn't change.
      if updated == 0 or updated == mx:
        return False
      heapq.heappush(maxHeap, -updated)
      summ = summ - mx + updated

    return True