Skip to content

2554. Maximum Number of Integers to Choose From a Range I #920

Answered by mah-shamim
mah-shamim asked this question in Q&A
Discussion options

You must be logged in to vote

We can use a greedy approach where we iterate over the numbers from 1 to n, skipping the banned numbers, and keep adding the valid numbers (those not in the banned array) to a running sum until we reach the maxSum.

Here's the step-by-step solution:

Steps:

  1. Convert banned array to a set for quick lookups: Using array_flip() can convert the banned array into a set for O(1) average-time complexity lookups.
  2. Iterate from 1 to n: Check each number, if it's not in the banned set and if adding it doesn't exceed maxSum, add it to the sum and increase the count.
  3. Stop once adding the next number exceeds maxSum: Since the goal is to maximize the number of chosen integers without exceeding the sum, th…

Replies: 1 comment 2 replies

Comment options

mah-shamim
Dec 6, 2024
Maintainer Author

You must be logged in to vote
2 replies
@kovatz
Comment options

kovatz Dec 6, 2024
Collaborator

@mah-shamim
Comment options

mah-shamim Dec 6, 2024
Maintainer Author

Answer selected by kovatz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested medium Difficulty
2 participants