Leetcode Problem 2557. Maximum Number of Integers to Choose From a Range II

2557. Maximum Number of Integers to Choose From a Range II

Leetcode Solutions

Greedy Approach with Quadratic Equation

  1. Calculate the initial sum k using the quadratic equation k = min(n, int((-1 + sqrt(1 + 8 * maxSum)) / 2)).
  2. Initialize currentSum to k * (k + 1) / 2 and count to k.
  3. Create a set bannedSet from the banned array.
  4. Iterate through bannedSet and for each banned number b that is less than or equal to k, subtract b from currentSum and decrement count.
  5. Iterate from k + 1 to n and for each non-banned number, add it to currentSum and increment count until currentSum exceeds maxSum.
  6. Return the final count.
UML Thumbnail

Greedy Approach with Sorting and Interval Summation

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...