forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
minimum-operations-to-form-subsequence-with-target-sum.py
137 lines (122 loc) · 3.37 KB
/
minimum-operations-to-form-subsequence-with-target-sum.py
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
# Time: O(n)
# Space: O(logn)
# codeforces, https://codeforces.com/problemset/problem/1303/D
# counting sort, greedy
class Solution(object):
def minOperations(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
def floor_log2_x(x):
return x.bit_length()-1
total = sum(nums)
if total < target:
return -1
cnt = [0]*(floor_log2_x(max(nums))+1)
for x in nums:
cnt[floor_log2_x(x)] += 1
result = 0
for i in reversed(xrange(len(cnt))):
for _ in xrange(cnt[i]):
x = 1<<i
if x <= target:
target -= x
total -= x
elif total-x >= target:
total -= x
else:
cnt[i-1] += 2
result += 1
return result
# Time: O(nlogn)
# Space: O(1)
# codeforces, https://codeforces.com/problemset/problem/1303/D
# sort, greedy
class Solution2(object):
def minOperations(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
total = sum(nums)
if total < target:
return -1
nums.sort()
result = 0
while target:
x = nums.pop()
if x <= target:
target -= x
total -= x
elif total-x >= target:
total -= x
else:
nums.append(x//2)
nums.append(x//2)
result += 1
return result
# Time: O(nlogn)
# Space: O(n)
import heapq
# codeforces, https://codeforces.com/problemset/problem/1303/D
# heap, greedy
class Solution3(object):
def minOperations(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
total = sum(nums)
if total < target:
return -1
result = 0
max_heap = [-x for x in nums]
heapq.heapify(max_heap)
while target:
x = -heapq.heappop(max_heap)
if x <= target:
target -= x
total -= x
elif total-x >= target:
total -= x
else:
heapq.heappush(max_heap, -x//2)
heapq.heappush(max_heap, -x//2)
result += 1
return result
# Time: O(nlogr)
# Space: O(logr)
# codeforces, https://codeforces.com/problemset/problem/1303/D
# bitmasks, greedy
class Solution4(object):
def minOperations(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
def floor_log2_x(x):
return x.bit_length()-1
if sum(nums) < target:
return -1
cnt = [0]*(floor_log2_x(max(nums))+1)
for x in nums:
cnt[floor_log2_x(x)] += 1
result = i = 0
while i < len(cnt):
if target&(1<<i):
if not cnt[i]:
j = next(j for j in xrange(i, len(cnt)) if cnt[j])
result += j-i
j = i
cnt[i] -= 1
continue
cnt[i] -= 1
if i+1 < len(cnt):
cnt[i+1] += cnt[i]//2
i += 1
return result