Leetcode 2554: Maximum Number of Integers to Choose From a Range I

grid47
grid47
Exploring patterns and algorithms
Feb 25, 2024 6 min read

You are given an array banned consisting of integers, an integer n, and an integer maxSum. Your task is to return the maximum number of integers you can select from the range [1, n] such that none of them are in the banned list and their sum does not exceed maxSum.
Problem
Approach
Steps
Complexity
Input: You are given an array `banned` containing integers, an integer `n` representing the upper limit of the range, and an integer `maxSum` representing the sum limit.
Example: banned = [3, 7, 5], n = 6, maxSum = 10
Constraints:
• 1 <= banned.length <= 10^4
• 1 <= banned[i], n <= 10^4
• 1 <= maxSum <= 10^9
Output: Return the maximum number of integers you can select from the range [1, n] without exceeding `maxSum` and ensuring none of them are in the `banned` array.
Example: 3
Constraints:
Goal: Maximize the count of integers selected from [1, n] under the given constraints.
Steps:
• 1. Loop through the range [1, n] and for each integer, check if it is in the banned list and if adding it would exceed maxSum.
• 2. If the integer is not in the banned list and does not exceed the sum limit, add it to the selection and update the remaining sum.
• 3. Stop the selection once the sum exceeds maxSum.
Goal: Ensure the solution works for both small and large inputs as described in the constraints.
Steps:
• 1 <= banned.length <= 10^4
• 1 <= banned[i], n <= 10^4
• 1 <= maxSum <= 10^9
Assumptions:
• The array `banned` does not contain duplicate values.
• All integers in the range [1, n] are distinct.
Input: banned = [3, 7, 5], n = 6, maxSum = 10
Explanation: You can choose integers 1, 2, and 6. The sum of 1 + 2 + 6 = 9, which is under the maxSum of 10.

Input: banned = [1, 2, 3], n = 5, maxSum = 4
Explanation: The only integer you can choose is 4 because all others are banned.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus