The Maximum Number of Integers to Choose From a Range I coding problem gives you a list of banned integers, a range [1, n], and a sum limit maxSum. You want to choose the maximum number of distinct integers from [1, n] that are not banned and whose total sum does not exceed maxSum.
Microsoft, PayPal, and Amazon include this problem as a clean greedy problem that tests set lookup and sequential selection. The optimal strategy is to always pick the smallest available unbanned integers first (to maximize count). Using a hash set for banned numbers makes the lookup O(1), enabling an O(n) greedy pass.
Greedy with hash set: Store banned integers in a hash set. Iterate from 1 to n. For each integer, if it's not banned and adding it keeps the sum ≤ maxSum, include it. Stop when the sum would exceed maxSum or you've processed all integers. This greedy always picks smallest-first, maximizing count. Time: O(n + len(banned)).
A binary search variant sorts non-banned integers and binary searches for the maximum prefix sum ≤ maxSum, but the linear greedy is simpler and equally correct.
banned = [1, 6, 5], n = 5, maxSum = 6.
For the Array Hash Table Sorting Binary Search Greedy interview pattern, whenever a problem says "pick maximum count subject to sum constraint, avoiding a banned set," greedy smallest-first is optimal. A sorted banned set can be skipped more efficiently, but the hash set approach is simpler to code under time pressure. Know both.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Maximum Number of Integers to Choose From a Range II | Medium | Solve | |
| Hand of Straights | Medium | Solve | |
| Maximize Score of Numbers in Ranges | Medium | Solve | |
| Divide Array in Sets of K Consecutive Numbers | Medium | Solve | |
| Maximum Tastiness of Candy Basket | Medium | Solve |