Skip to main content
Back to problems
#2554
Medium Algorithms

Maximum number of integers to choose from a range i

Array Hash Table Binary Search Greedy Sorting
68.0% acceptance
Feb 25, 2026
826
57
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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn max_count(banned: Vec<i32>, n: i32, max_sum: i32) -> i32 {
    let banned_set: std::collections::HashSet<i32> = banned.into_iter().collect();
    let mut count = 0;
    let mut sum = 0i64;
    for i in 1..=n {
      if banned_set.contains(&i) {
        continue;
      }
      if sum + i as i64 > max_sum as i64 {
        break;
      }
      sum += i as i64;
      count += 1;
    }
    count
  }
}