给你一个整数数组 banned
和两个整数 n
和 maxSum
。你需要按照以下规则选择一些整数:
- 被选择整数的范围是
[1, n]
。 - 每个整数 至多 选择 一次 。
- 被选择整数不能在数组
banned
中。 - 被选择整数的和不超过
maxSum
。
请你返回按照上述规则 最多 可以选择的整数数目。
示例 1:
输入:banned = [1,4,6], n = 6, maxSum = 4 输出:1 解释:你可以选择整数 3 。 3 在范围 [1, 6] 内,且不在 banned 中,所选整数的和为 3 ,也没有超过 maxSum 。
示例 2:
输入:banned = [4,3,5,6], n = 7, maxSum = 18 输出:3 解释:你可以选择整数 1, 2 和 7 。 它们都在范围 [1, 7] 中,且都没出现在 banned 中,所选整数的和为 10 ,没有超过 maxSum 。
提示:
1 <= banned.length <= 105
1 <= banned[i] <= n <= 109
1 <= maxSum <= 1015
我们可以在数组 banned
中加入 banned
去重并排序。
接下来,我们枚举数组 banned
中的每两个相邻元素 maxSum
中减去这些元素的和。如果 maxSum
小于
时间复杂度 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 pairwise(ban):
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
class Solution {
public int maxCount(int[] banned, int n, long maxSum) {
Set<Integer> black = new HashSet<>();
black.add(0);
black.add(n + 1);
for (int x : banned) {
black.add(x);
}
List<Integer> ban = new ArrayList<>(black);
Collections.sort(ban);
int ans = 0;
for (int k = 1; k < ban.size(); ++k) {
int i = ban.get(k - 1), j = ban.get(k);
int left = 0, right = j - i - 1;
while (left < right) {
int mid = (left + right + 1) >>> 1;
if ((i + 1 + i + mid) * 1L * mid / 2 <= maxSum) {
left = mid;
} else {
right = mid - 1;
}
}
ans += left;
maxSum -= (i + 1 + i + left) * 1L * left / 2;
if (maxSum <= 0) {
break;
}
}
return ans;
}
}
class Solution {
public:
int maxCount(vector<int>& banned, int n, long long maxSum) {
banned.push_back(0);
banned.push_back(n + 1);
sort(banned.begin(), banned.end());
banned.erase(unique(banned.begin(), banned.end()), banned.end());
int ans = 0;
for (int k = 1; k < banned.size(); ++k) {
int i = banned[k - 1], j = banned[k];
int left = 0, right = j - i - 1;
while (left < right) {
int mid = left + ((right - left + 1) / 2);
if ((i + 1 + i + mid) * 1LL * mid / 2 <= maxSum) {
left = mid;
} else {
right = mid - 1;
}
}
ans += left;
maxSum -= (i + 1 + i + left) * 1LL * left / 2;
if (maxSum <= 0) {
break;
}
}
return ans;
}
};
func maxCount(banned []int, n int, maxSum int64) (ans int) {
banned = append(banned, []int{0, n + 1}...)
sort.Ints(banned)
ban := []int{}
for i, x := range banned {
if i > 0 && x == banned[i-1] {
continue
}
ban = append(ban, x)
}
for k := 1; k < len(ban); k++ {
i, j := ban[k-1], ban[k]
left, right := 0, j-i-1
for left < right {
mid := (left + right + 1) >> 1
if int64((i+1+i+mid)*mid/2) <= maxSum {
left = mid
} else {
right = mid - 1
}
}
ans += left
maxSum -= int64((i + 1 + i + left) * left / 2)
if maxSum <= 0 {
break
}
}
return
}