Maximum Number of Integers to Choose From a Range II Problem
Description
LeetCode Problem 2557.
You are given an integer array banned and two integers n and maxSum. You are choosing some number of integers following the below rules:
- The chosen integers have to be in the range
[1, n]. - Each integer can be chosen at most once.
- The chosen integers should not be in the array
banned. - The sum of the chosen integers should not exceed
maxSum.
Return the maximum number of integers you can choose following the mentioned rules.
Example 1:
Input: banned = [1,4,6], n = 6, maxSum = 4
Output: 1
Explanation: You can choose the integer 3.
3 is in the range [1, 6], and do not appear in banned. The sum of the chosen integers is 3, which does not exceed maxSum.
Example 2:
Input: banned = [4,3,5,6], n = 7, maxSum = 18
Output: 3
Explanation: You can choose the integers 1, 2, and 7.
All these integers are in the range [1, 7], all do not appear in banned, and their sum is 10, which does not exceed maxSum.
Constraints:
1 <= banned.length <= 10^51 <= banned[i] <= n <= 10^91 <= maxSum <= 10^15
Solution
Approach: Sort and Binary Search per Gap
Add 0 and n + 1 to banned, then remove duplicates and sort. The numbers we may pick lie in the gaps between neighbouring banned values i and j, that is, in [i + 1, j - 1].
Within a gap it is best to take the smallest numbers first, and the sum of the first m of them is (i + 1 + i + m) * m / 2. Binary search the largest m (at most j - i - 1) whose sum fits in the remaining maxSum. Add m to the answer, subtract the sum from maxSum, and stop when nothing is left.
Complexity: O(b log b + b log n) time and O(b) extra space, where b is the length of banned.
class Solution:
def maxCount(self, banned: List[int], n: int, maxSum: int) -> int:
banned.extend([0, n + 1])
ban = sorted(set(banned))
ans = 0
for i, j in zip(ban, ban[1:]):
left, right = 0, j - i - 1
while left < right:
mid = (left + right + 1) >> 1
if (i + 1 + i + mid) * mid // 2 <= maxSum:
left = mid
else:
right = mid - 1
ans += left
maxSum -= (i + 1 + i + left) * left // 2
if maxSum <= 0:
break
return ans