Maximum Number of Integers to Choose From a Range I

medium greedy hash table sorting

Problem

Given an array banned and integers n and maxSum, choose integers from the range [1, n]. Each integer may be chosen at most once, no chosen integer may appear in banned, and the sum of chosen integers must not exceed maxSum. Return the maximum count of integers you can choose.

To maximize how many numbers fit under the budget, always prefer the smallest available value first — small numbers cost less, leaving more room for further picks.

Inputbanned = [1,6,5], n = 5, maxSum = 6
Output2
Choose 2 and 4: both lie in [1, 5], neither is banned, and 2 + 4 = 6 ≤ maxSum.

def maxCount(banned, n, maxSum):
    # Only banned values inside [1, n] can ever interfere.
    blocked = {b for b in banned if b <= n}
    total = 0      # running sum of chosen integers
    count = 0      # how many we have chosen
    # Greedy: smallest allowed numbers first.
    for num in range(1, n + 1):
        if num in blocked:
            continue
        if total + num > maxSum:
            break          # budget would be exceeded
        total += num
        count += 1
    return count
function maxCount(banned, n, maxSum) {
  // Only banned values inside [1, n] can ever interfere.
  const blocked = new Set(banned.filter(b => b <= n));
  let total = 0;   // running sum of chosen integers
  let count = 0;   // how many we have chosen
  // Greedy: smallest allowed numbers first.
  for (let num = 1; num <= n; num++) {
    if (blocked.has(num)) continue;
    if (total + num > maxSum) break;  // budget exceeded
    total += num;
    count++;
  }
  return count;
}
int maxCount(int[] banned, int n, int maxSum) {
    // Only banned values inside [1, n] can ever interfere.
    Set<Integer> blocked = new HashSet<>();
    for (int b : banned) if (b <= n) blocked.add(b);
    long total = 0;   // running sum of chosen integers
    int count = 0;    // how many we have chosen
    // Greedy: smallest allowed numbers first.
    for (int num = 1; num <= n; num++) {
        if (blocked.contains(num)) continue;
        if (total + num > maxSum) break;  // budget exceeded
        total += num;
        count++;
    }
    return count;
}
int maxCount(vector<int>& banned, int n, int maxSum) {
    // Only banned values inside [1, n] can ever interfere.
    unordered_set<int> blocked;
    for (int b : banned) if (b <= n) blocked.insert(b);
    long long total = 0;  // running sum of chosen integers
    int count = 0;        // how many we have chosen
    // Greedy: smallest allowed numbers first.
    for (int num = 1; num <= n; num++) {
        if (blocked.count(num)) continue;
        if (total + num > maxSum) break;  // budget exceeded
        total += num;
        count++;
    }
    return count;
}
Time: O(n + banned.length) Space: O(banned.length)