Input: banned =[1,4,6], n =6, maxSum =4Output: 1Explanation: You can choose the integer 3.3isin the range [1,6], and do not appear in banned. The sum of the chosen integers is3, which does not exceed maxSum.
Input: banned =[4,3,5,6], n =7, maxSum =18Output: 3Explanation: 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 is18, which does not exceed maxSum.
To maximize the count of chosen numbers, always pick the smallest available number not in banned and keep adding until the sum exceeds maxSum. Skipping banned numbers ensures we only consider valid picks.
classSolution {
public:int maxCount(vector<int>& banned, int n, int maxSum) {
unordered_set<int> ban(banned.begin(), banned.end());
int ans =0;
longlong curr_sum =0;
for (int i =1; i <= n; ++i) {
if (ban.count(i)) continue;
if (curr_sum + i > maxSum) break;
curr_sum += i;
++ans;
}
return ans;
}
};
classSolution {
publicintmaxCount(int[] banned, int n, int maxSum) {
Set<Integer> ban =new HashSet<>();
for (int b : banned) ban.add(b);
int ans = 0;
long currSum = 0;
for (int i = 1; i <= n; i++) {
if (ban.contains(i)) continue;
if (currSum + i > maxSum) break;
currSum += i;
ans++;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
funmaxCount(banned: IntArray, n: Int, maxSum: Int): Int {
val ban = banned.toHashSet()
var ans = 0var currSum = 0Lfor (i in1..n) {
if (i in ban) continueif (currSum + i > maxSum) break currSum += i
ans++ }
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defmaxCount(self, banned: list[int], n: int, maxSum: int) -> int:
ban = set(banned)
ans =0 curr_sum =0for i in range(1, n +1):
if i in ban:
continueif curr_sum + i > maxSum:
break curr_sum += i
ans +=1return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
use std::collections::HashSet;
impl Solution {
pubfnmax_count(banned: Vec<i32>, n: i32, max_sum: i64) -> i32 {
let ban: HashSet<i32>= banned.into_iter().collect();
letmut ans =0;
letmut curr_sum =0i64;
for i in1..=n {
if ban.contains(&i) { continue; }
if curr_sum + i asi64> max_sum { break; }
curr_sum += i asi64;
ans +=1;
}
ans
}
}