#2554

Maximum Number of Integers to Choose From a Range I

Medium
ArrayHash TableBinary SearchGreedySortingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(n)
O(n)
💡

Intuition

Time O(n)Space O(n)

Instead of checking each integer individually, we can iterate through the numbers from 1 to n, skipping the banned numbers and keeping track of the sum. This way, we can efficiently determine how many integers we can select without exceeding maxSum.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create a set from the banned array for O(1) lookups.
  2. 2Step 2: Initialize a variable to keep track of the sum of chosen integers and a counter for the number of integers chosen.
  3. 3Step 3: Loop through each integer from 1 to n, check if it's not in the banned set.
  4. 4Step 4: If it's not banned and adding it to the sum does not exceed maxSum, add it to the sum and increment the counter.
  5. 5Step 5: If adding the next integer exceeds maxSum, break the loop.
solution.py12 lines
1def maxIntegers(banned, n, maxSum):
2    banned_set = set(banned)
3    total_sum = 0
4    count = 0
5    for i in range(1, n + 1):
6        if i not in banned_set:
7            if total_sum + i <= maxSum:
8                total_sum += i
9                count += 1
10            else:
11                break
12    return count

Complexity note: The time complexity is O(n) since we only loop through the range once, and the space complexity is O(n) for storing the banned set.

  • 1Using a set for banned numbers allows for quick lookups.
  • 2Iterating through the range and checking conditions in a single pass is efficient.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.