Maximum Number of Integers to Choose from a Range I

Greedily pick the smallest unbanned numbers from 1..n until you exceed maxSum.

Medium
Time O(n + b log b) Space O(b)
LeetCode
3 min read
greedy hashing

Problem#

Pick integers from [1, n] excluding any in banned, with total sum at most maxSum. Return the maximum count of distinct integers chosen.

Examples#

  • banned = [1,6,5], n = 5, maxSum = 62 (pick 2 and 4)
  • banned = [1,2,3,4,5,6,7], n = 8, maxSum = 10
  • banned = [11], n = 7, maxSum = 507

Constraints#

  • 1 <= banned.length <= 10^4, 1 <= banned[i], n <= 10^4, 1 <= maxSum <= 10^9.

Approach#

Smaller numbers always pay less per pick — greedy is optimal. Put banned into a hash set; iterate i = 1..n, accumulate sum, count picks until adding i would exceed maxSum.

Solution#

Maximum Number of Integers to Choose from a Range I
class Solution {
public:
int maxCount(vector<int>& banned, int n, int maxSum) {
unordered_set<int> bad(banned.begin(), banned.end());
long sum = 0;
int count = 0;
for (int i = 1; i <= n; ++i) {
if (bad.count(i)) continue;
if (sum + i > maxSum) break;
sum += i;
++count;
}
return count;
}
};

Editorial#

Greedy works because the count we want is independent of which numbers we choose — only the sum matters. Picking the smallest valid candidates minimizes sum per increment of count.

Complexity#

  • Time: O(n + b) where b is banned size.
  • Space: O(b).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.