2554. Maximum Number of Integers to Choose From a Range I - Detailed Explanation

Problem Statement

You are given two positive integers, n and maxSum. The task is to choose some number of distinct integers from the range [1, n] such that their total sum does not exceed maxSum. Return the maximum number of integers you can choose.

Example 1

  • Input: n = 4, maxSum = 6
  • Output: 3
  • Explanation: The optimal selection is [1, 2, 3] with a sum of 6. Although 4 is available, 1 + 2 + 3 + 4 = 10 exceeds maxSum.

Example 2

  • Input: n = 5, maxSum = 15
  • Output: 5
  • Explanation: You can choose all the integers [1, 2, 3, 4, 5] because their sum is exactly 15.

Example 3

  • Input: n = 2, maxSum = 1
  • Output: 1
  • Explanation: The only valid selection is [1] since 1 ≤ maxSum, and choosing 2 would exceed it.

Constraints:

  • 1 ≤ n
  • 1 ≤ maxSum
  • (n and maxSum can be large, so an efficient solution is needed.)

Hints

  1. Greedy Insight:
    To maximize the number of integers while keeping the sum as small as possible, you should choose the smallest available numbers first.

  2. Sum Formula:
    The sum of the first k natural numbers is given by the formula:
    [ \text{sum} = \frac{k(k+1)}{2} ] Use this formula to determine the largest k such that (\frac{k(k+1)}{2} \leq \text{maxSum}). However, remember that you cannot choose more than n integers, so the answer is the minimum between n and this k.

Approaches

Greedy / Mathematical Approach

  • Idea:
    The optimal way to maximize the count is to start with the smallest numbers. The sum of the first k natural numbers is the smallest possible sum for k distinct numbers in the range [1, n]. Find the largest k such that: [ \frac{k(k+1)}{2} \leq \text{maxSum} ] Then, the answer is: [ \text{answer} = \min(n, k) ]

  • Steps:

    1. Use the quadratic formula to solve the inequality: [ k^2 + k - 2 \times \text{maxSum} \leq 0 ]
    2. Compute: [ k_{\text{candidate}} = \left\lfloor \frac{\sqrt{1 + 8 \times \text{maxSum}} - 1}{2} \right\rfloor ]
    3. The final answer is: [ \min(n, k_{\text{candidate}}) ]
  • Complexity:

    • Time: O(1) – Constant time arithmetic operations.
    • Space: O(1)

Binary Search Approach

  • Idea:
    Instead of using a closed-form solution, use binary search to find the maximum k such that: [ \frac{k(k+1)}{2} \leq \text{maxSum} ] Iterate over the possible values of k (from 0 to n) to find the largest valid k.

  • Steps:

    1. Initialize two pointers: low = 0 and high = n.
    2. While low ≤ high, compute mid = low + (high - low) // 2.
    3. If (\frac{\text{mid} \times (\text{mid} + 1)}{2} \leq \text{maxSum}), then move the search to the right (i.e., set low = mid + 1).
    4. Otherwise, move the search to the left (i.e., set high = mid - 1).
    5. The largest mid that satisfies the condition is your candidate, and the answer is: [ \min(n, \text{candidate}) ]
  • Complexity:

    • Time: O(log n)
    • Space: O(1)

Complexity Analysis

  • Greedy / Mathematical Approach:

    • Time: O(1)
    • Space: O(1)
  • Binary Search Approach:

    • Time: O(log n)
    • Space: O(1)

Python Code

Python3
Python3

. . . .

Java Code

Java
Java

. . . .

Step-by-Step Walkthrough and Visual Examples

Example Walkthrough for n = 4, maxSum = 6

  1. Understanding the Problem:
    You have the integers [1, 2, 3, 4]. To maximize the count of numbers chosen without exceeding a sum of 6, you should start from 1.

  2. Greedy Selection:

    • First, choose 1 → Sum = 1
    • Then, choose 2 → Sum = 1 + 2 = 3
    • Then, choose 3 → Sum = 1 + 2 + 3 = 6
    • Adding the next integer, 4, would yield a sum of 10, which exceeds maxSum.
  3. Calculation using the Formula:

    • We need the largest k such that: [ \frac{k(k+1)}{2} \leq 6 ]
    • Plug in k = 3: [ \frac{3 \times 4}{2} = 6 \leq 6 ]
    • k = 3 works.
    • Since n = 4 and k_candidate = 3, the answer is min(4, 3) = 3.
  4. Result:
    The maximum number of integers that can be chosen is 3.

Common Mistakes

  • Off-by-One Errors:
    Incorrectly computing the sum of the first k natural numbers or not including the boundary conditions properly.

  • Ignoring the Upper Bound n:
    Forgetting to take the minimum of n and the computed k might result in an answer that exceeds the available range.

  • Floating Point Precision:
    Not correctly handling the conversion from the result of the square root calculation to an integer, which can lead to rounding issues.

Edge Cases

  • maxSum is Very Small:
    If maxSum is so small that even the smallest integer (1) cannot be chosen, then no integers can be selected (although per constraints, maxSum is at least 1).

  • maxSum Exactly Equals Sum of 1 to n:
    When: [ \frac{n(n+1)}{2} = \text{maxSum} ] then the answer is n since all numbers can be chosen.

  • Large n with Limited maxSum:
    Even if n is very large, a small maxSum will restrict the number of integers you can choose.

Alternative Variations

  • Return the Chosen Integers:
    Modify the problem so that, instead of just returning the count, you return the actual list of integers selected (which will always be the sequence [1, 2, …, k]).

  • Different Range:
    Consider a variation where the integers are chosen from a different range, such as [a, b], instead of [1, n].

TAGS
leetcode
CONTRIBUTOR
Design Gurus Team
-

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
Related Courses
Grokking the Coding Interview: Patterns for Coding Questions
Grokking the Coding Interview Patterns in Java, Python, JS, C++, C#, and Go. The most comprehensive course with 476 Lessons.
4.6
(69,299 learners)
New
Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
3.9
(1,107 learners)
Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
4
(26,683 learners)
Image
One-Stop Portal For Tech Interviews.
Copyright © 2025 Design Gurus, LLC. All rights reserved.