Maximum Number of Integers to Choose From a Range II - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
banned = [2,6], n = 7, maxSum = 15
›
Output:
4
💡 Note:
We can choose [1,3,4,5]. These are not banned and sum to 13 ≤ 15. Cannot add 7 as 13+7=20 > 15.
Example 2 — Small Budget
$
Input:
banned = [1,3], n = 4, maxSum = 4
›
Output:
1
💡 Note:
Available numbers are [2,4]. We can only pick 2 (sum=2 ≤ 4). Adding 4 would make sum=6 > 4.
Example 3 — All Numbers Available
$
Input:
banned = [], n = 3, maxSum = 6
›
Output:
3
💡 Note:
No numbers are banned. We can pick [1,2,3] with sum=6 ≤ 6, selecting all 3 numbers.
Constraints
- 1 ≤ banned.length ≤ 104
- 1 ≤ banned[i], n ≤ 104
- 1 ≤ maxSum ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input Analysis
Range [1,n], banned numbers, and sum limit maxSum
2
Greedy Selection
Pick smallest available numbers first to maximize count
3
Result
Maximum count of integers that satisfy all constraints
Key Takeaway
🎯 Key Insight: Greedy approach works because smaller numbers allow more selections within the sum limit
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code