Problem Description
Given an array target of n integers, determine if it is possible to construct target starting from an array arr of n ones. In each step, you can choose an index i and replace arr[i] with the sum of all elements in arr. Return true if the sequence of operations can convert arr to target, otherwise return false.
Key Insights
- Instead of simulating the forward sum operations, work backwards from target.
- The largest element in target must have been created by summing the rest of the array.
- Use a maximum heap to efficiently extract the largest element.
- At each step, let x be the maximum element and rest be the sum of all other elements.
- The previous value of x must have been x % rest (if rest is not 1), since multiple operations may have been applied.
- Edge cases include when rest is 0 or when x is less than or equal to rest.
Space and Time Complexity
Time Complexity: O(n log n) where n is the number of elements in target (each heap operation takes O(log n)). Space Complexity: O(n) for storing the heap.
Solution
The solution reverses the operation by always taking the largest element x from target and computing the hypothetical previous value before x was updated. The rest of the array has sum rest = total - x. If rest is 0 or x <= rest, we know that it's impossible to have reached the current state. Otherwise, compute new_x = x % rest. If new_x is 0, set new_x = rest. Update the total sum and push the new value back into the max-heap. Continue until every element reduces to 1 or until the operation is no longer possible.