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.
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 01:
-
C++
-
Python
class Solution { public: int maxCount(vector<int>& banned, int n, int maxSum) { unordered_set<int> bannedSet(begin(banned), end(banned)); int validCount = 0; int currentSum = 0; for (int currentNum = 1; currentNum <= n; currentNum++) { if (bannedSet.count(currentNum)) { continue; } if (currentSum + currentNum <= maxSum) { validCount++; currentSum += currentNum; } else { break; } } return validCount; } };
class Solution: def maxCount(self, banned: list[int], n: int, maxSum: int) -> int: bannedSet = set(banned) validCount = 0 currentSum = 0 for currentNum in range(1, n + 1): if currentNum in bannedSet: continue if currentSum + currentNum <= maxSum: validCount += 1 currentSum += currentNum else: break return validCount
Time Complexity
- Creating the banned set:
The banned vector is converted into an unordered set, which requires iterating over the elements of
banned
. If the size ofbanned
is \(M\), this step takes \(O(M)\). - Iterating from 1 to
n
:The loop iterates at most \(n\) times. Each iteration involves checking membership in the
bannedSet
, which is an \(O(1)\) operation on average due to hash-based lookups. Thus, the loop takes \(O(n)\). - Overall Time Complexity:
The overall time complexity is \(O(M + n)\), where \(M\) is the size of the banned list and \(n\) is the maximum number to consider.
Space Complexity
- Space for the
bannedSet
:The
bannedSet
stores all elements from thebanned
vector. If the size ofbanned
is \(M\), this requires \(O(M)\) space. - Auxiliary variables:
The function uses a few integer variables (
validCount
,currentSum
, andcurrentNum
), which require \(O(1)\) space. - Overall Space Complexity:
The overall space complexity is \(O(M)\) to store the banned set.