Problem Description
Given an integer array banned, an integer n, and an integer maxSum, select a subset of integers from the range [1, n] such that:
- Each integer is chosen at most once.
- None of the integers is present in the banned array.
- The sum of the chosen integers does not exceed maxSum. Return the maximum number of integers that can be chosen while satisfying these rules.
Key Insights
- Use a set for banned numbers to allow quick lookups.
- Greedily select the smallest numbers from 1 to n to maximize the count, as smaller numbers allow for a minimal sum.
- Maintain a running sum and count; stop when adding the next eligible number would exceed maxSum.
- The approach is simple and efficient given the constraints.
Space and Time Complexity
Time Complexity: O(n) (plus O(m) for creating the banned set, where m is the length of banned, overall linear) Space Complexity: O(n) (due to storing banned numbers in a set)
Solution
The solution uses a greedy algorithm. First, convert the banned list into a set for O(1) membership checks. Then, iterate through integers from 1 to n. For each integer, if it is not in the banned set and adding it to the current sum does not exceed maxSum, then include it and update the sum and counter. The iteration stops either when all numbers have been considered or when the next eligible integer would make the sum exceed maxSum.