Skip to content

Commit e5df9cb

Browse files
authored
Create construct-target-array-with-multiple-sums.py
1 parent 28df685 commit e5df9cb

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Time: O(log(max(t)) * logn)
2+
# Space: O(n)
3+
4+
import heapq
5+
6+
7+
class Solution(object):
8+
def isPossible(self, target):
9+
"""
10+
:type target: List[int]
11+
:rtype: bool
12+
"""
13+
# (1) x + remain = y
14+
# (2) y + remain = total
15+
# (1) - (2) => x - y = y - total
16+
# => x = 2*y - total
17+
total = sum(target)
18+
max_heap = [-x for x in target]
19+
heapq.heapify(max_heap)
20+
while total != len(target):
21+
y = -heapq.heappop(max_heap)
22+
remain = total-y
23+
x = y-remain
24+
if x <= 0:
25+
return False
26+
if x > remain: # for case [1, 1000000000]
27+
x = x%remain + remain
28+
heapq.heappush(max_heap, -x)
29+
total = x+remain
30+
return True

0 commit comments

Comments
 (0)