Skip to content

Commit 96aa127

Browse files
authored
Update maximum-number-of-integers-to-choose-from-a-range-ii.py
1 parent 6467945 commit 96aa127

File tree

1 file changed

+31
-2
lines changed

1 file changed

+31
-2
lines changed

Python/maximum-number-of-integers-to-choose-from-a-range-ii.py

+31-2
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,40 @@
1-
# Time: O(blogb + logn * logb)
1+
# Time: O(b)
22
# Space: O(b)
33

4+
# math
5+
class Solution(object):
6+
def maxCount(self, banned, n, maxSum):
7+
"""
8+
:type banned: List[int]
9+
:type n: int
10+
:type maxSum: int
11+
:rtype: int
12+
"""
13+
k = min(int((-1+(1+8*maxSum))**0.5/2), n) # k = argmax((k+1)*k//2 <= maxSum)
14+
total = (k+1)*k//2
15+
result = k
16+
lookup = set(banned)
17+
for x in lookup:
18+
if x <= k:
19+
total -= x
20+
result -= 1
21+
for i in xrange(k+1, n+1):
22+
if i in lookup:
23+
continue
24+
if total+i > maxSum:
25+
break
26+
total += i
27+
result += 1
28+
return result
29+
30+
31+
# Time: O(blogb + logn * logb)
32+
# Space: O(b)
433
import bisect
534

635

736
# binary search, prefix sum
8-
class Solution(object):
37+
class Solution2(object):
938
def maxCount(self, banned, n, maxSum):
1039
"""
1140
:type banned: List[int]

0 commit comments

Comments
 (0)