Maximum Number of Integers to Choose From a Range I

Updated on 12 June, 2025
Maximum Number of Integers to Choose From a Range I header image

Problem Statement

In this task, we are given an array named banned and two integers, n and maxSum. The objective is to select a subset of integers from the range [1, n] such that:

  1. Each selected integer is chosen only once.
  2. None of the selected integers are present in the banned array.
  3. The cumulative sum of the selected integers does not exceed maxSum.

The goal is to maximize the count of integers that can be selected under these constraints. The function should return this maximum count of integers.

Examples

Example 1

Input:

banned = [1,6,5], n = 5, maxSum = 6

Output:

2

Explanation:

You can choose the integers 2 and 4.
2 and 4 are from the range [1, 5], both did not appear in banned, and their sum is 6, which did not exceed maxSum.

Example 2

Input:

banned = [1,2,3,4,5,6,7], n = 8, maxSum = 1

Output:

0

Explanation:

You cannot choose any integer while following the mentioned conditions.

Example 3

Input:

banned = [11], n = 7, maxSum = 50

Output:

7

Explanation:

You can choose the integers 1, 2, 3, 4, 5, 6, and 7.
They are from the range [1, 7], all did not appear in banned, and their sum is 28, which did not exceed maxSum.

Constraints

  • 1 <= banned.length <= 104
  • 1 <= banned[i], n <= 104
  • 1 <= maxSum <= 109

Approach and Intuition

The problem involves optimizing the selection of integers so as to maximize the number under specific constraints. Here's a step-by-step approach to solve this problem:

  1. Identify Unbanned Numbers:

    • First, we need to determine which numbers between 1 and n are not in the banned list. This can be efficiently handled using a set to store banned numbers and then iterating through the range to filter out these numbers.
  2. Sort and Sum:

    • Once we have the list of potential numbers to select from (those not banned and within the required range), sort this list. The rationale behind sorting is to start selecting from smaller numbers, hence maximizing the count of integers selected before reaching the maxSum limit.
  3. Select Numbers Under Sum Constraint:

    • Iterate through the sorted list of unbanned numbers, and keep a running total of the sum. Add numbers to the sum as long as it does not exceed maxSum.
    • Keep a count of how many numbers have been added. This count will be our answer to the maximum count of integers that can be selected within the defined constraints.

By following this method, we ensure that we are picking the maximum number of integers given the sum limitation by always choosing the smallest possible integers first, thereby optimizing the selection for quantity. This process utilizes straightforward computational steps and checks, making it efficient given the input constraints.

Solutions

  • C++
  • Java
  • Python
cpp
class Solution {
public:
    int countValidNumbers(vector<int>& restricts, int limit, int upperSum) {
        unordered_set<int> restrictedNums(restricts.begin(), restricts.end());

        int validCount = 0;

        for (int number = 1; number <= limit; number++) {
            if (restrictedNums.find(number) != restrictedNums.end()) continue;

            if (upperSum - number < 0) return validCount;

            upperSum -= number;
            validCount++;
        }
        return validCount;
    }
};

The C++ solution presented above is designed to calculate how many numbers you can choose from a range starting from 1 to the given limit, such that the sum of these chosen numbers does not exceed a specified upperSum, and the numbers are not in a given list of restricted numbers.

The following captures the process:

  • The code first initializes an unordered_set named restrictedNums with the numbers from the restricts vector to efficiently check if a number is restricted.
  • It initializes a counter validCount to keep track of how many numbers can be selected.
  • The function then iterates through all numbers from 1 to the specified limit.
  • For each number, it checks if the number is in the restrictedNums set. If it is, the loop continues to the next number, skipping the current one.
  • Next, it checks if the remaining allowance in upperSum after choosing the current number would be negative. If true, it terminates and returns the count (validCount) of numbers already chosen.
  • If valid, the current number is subtracted from upperSum, and validCount is incremented.
  • Finally, after the loop has processed all numbers up to limit, the total count of valid numbers that can be chosen is returned.

This method is efficient in terms of both time and space, as it only iterates through the numbers once and uses a set for quick membership checking. The use of early termination when the upperSum is exceeded, further optimizes the solution.

java
class Solution {

    public int maximumUsable(int[] exclude, int limit, int totalSum) {
        Set<Integer> excludedNumbers = new HashSet<>();
        for (int item : exclude) {
            excludedNumbers.add(item);
        }

        int validCount = 0;

        for (int i = 1; i <= limit; i++) {
            if (excludedNumbers.contains(i)) continue;

            if (totalSum - i < 0) return validCount;

            totalSum -= i;
            validCount++;
        }
        return validCount;
    }
}

This Java solution tackles the challenge of finding the maximum number of integers that can be chosen from a given range up to a specified limit, given a certain total sum and an array of numbers to exclude. Here's how the solution works:

  • Initialize a HashSet to store the excluded numbers for quick look-up.
  • Iterate over each number within the given range (from 1 to limit).
    • If the current number is in the set of excluded numbers, skip it.
    • Check if the total sum minus the current number is a negative value. If it is, the function returns the count of valid numbers found so far.
    • If the total sum is still zero or positive after subtracting the current number, decrease the total sum by the current integer and increment the count of valid numbers.
  • If the loop completes without the total sum becoming negative, return the count of valid numbers accumulated so far.

This ensures you dynamically exclude certain numbers and consider only the permissible sum for counting valid integers, making it efficient in checking conditions and managing the total sum dynamically. The use of a HashSet allows for fast exclusions checks, and careful iteration ensures that only viable options reduce the allowed sum.

python
class Solution:
    def maximumAvailable(self, forbidden: list[int], limit: int, totalMax: int) -> int:
        forbidden_nums = set(forbidden)
        allowed_count = 0

        for value in range(1, limit + 1):
            if value in forbidden_nums:
                continue

            if totalMax - value < 0:
                return allowed_count

            totalMax -= value
            allowed_count += 1

        return allowed_count

The given Python solution defines a method to calculate how many integers can be chosen from a range limited by a given limit and totalMax value, while avoiding a list of forbidden numbers. Here's how the solution works:

  • Convert the list of forbidden numbers into a set for efficient lookup.
  • Initialize a counter for the allowed integers.
  • Iterate over the range from 1 to limit.
    • Skip the iteration if the current number is in the set of forbidden numbers.
    • Check if subtracting the current number from totalMax would result in a negative value. If true, return the count of allowed integers so far.
    • Deduct the value of the current number from totalMax and increase the allowed integers counter.
  • Return the count of allowed integers after the loop ends.

This approach ensures that only integers that are not forbidden and do not exceed the totalMax when cumulatively added are counted.

Comments

No comments yet.