Statementâ–¼
Given an integer array banned
and two integers n
and max_sum
, determine the maximum number of integers you can choose while following the below rules:
The selected integers must fall within the range
[1,n] .Each integer can be chosen at most once.
No selected integer can be present in the
banned
array.The sum of the selected integers must not exceed
max_sum
.
Your goal is to return the maximum count of integers that can be chosen while satisfying all the above rules.
Constraints:
1≤ banned.length
≤103 1≤ banned[i]
≤ n
≤103 1≤ max_sum
≤109
Solution
To essence of the solution is to use the sort and search pattern. We first sort the banned array, then take advantage of the sorted nature of the sequence of numbers being evaluated and the sorted banned array.
The approach involves iterating through numbers from banned_idx
pointer to track the position in the banned array. This pointer helps determine whether the current number is banned by comparing it with the next value in the banned array. If the number matches the value pointed to by banned_idx
, it is skipped, and the pointer is moved to the next position in the banned array. This avoids scanning each number in the array.
As we iterate through the numbers, we add them to the count of valid integers if they are not banned. For each valid number, we subtract it from max_sum
. Suppose the subtraction causes max_sum
to drop below zero. In that case, we conclude the process and return the current count, representing the maximum number of integers that can be included without exceeding the maximum sum limit.
Now, let’s look at the solution:
Sort the
banned
array.Initialize the variables:
Start with a
banned_idx
pointer at0 to keep track of the current position in the banned array.Set a counter,
count
, and count to0 to record how many numbers are included.
Iterate through each number
i
—from1 ton .Compare the current number
i
with the value atbanned[banned_idx]
. Ifi
matchbanned[banned_idx]
, the number is banned. Skip this number and movebanned_idx
forward to the next position. Continue movingbanned_idx
until the next value is differs from the current one to handle duplicates.If the number is not banned, subtract its value from
max_sum
. After subtracting a valid number, stop iterating ifmax_sum
drops below0 . At this point, thecount
represents the maximum number of valid numbers that can be included without exceedingmax_sum
, so we return thecount
as the final result.Otherwise, increment the
count
to indicate that this number has been included and keep iterating.
After iterating through each number, return the total
count
of numbers included.
Let’s look at the following illustration to get a better understanding of the solution: