#1798

Maximum Number of Consecutive Values You Can Make

Medium
ArrayGreedySortingGreedySorting
LeetCode ↗

Approaches

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

Intuition

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

The optimal approach involves sorting the coins and using a greedy strategy to find the maximum consecutive values. If we can make all values up to x and have a coin of value v, we can then make all values up to x + v.

⚙️

Algorithm

5 steps
  1. 1Step 1: Sort the coins array.
  2. 2Step 2: Initialize a variable 'maxConsecutive' to 0.
  3. 3Step 3: Iterate through the sorted coins. For each coin, if it is greater than 'maxConsecutive + 1', break the loop.
  4. 4Step 4: Otherwise, add the coin value to 'maxConsecutive'.
  5. 5Step 5: Return 'maxConsecutive' + 1 as the result.
solution.py10 lines
1# Full working Python code
2
3def maxConsecutiveValues(coins):
4    coins.sort()
5    maxConsecutive = 0
6    for coin in coins:
7        if coin > maxConsecutive + 1:
8            break
9        maxConsecutive += coin
10    return maxConsecutive + 1

Complexity note: The time complexity is O(n log n) due to the sorting step, while the space complexity is O(1) since we are using a constant amount of extra space.

  • 1If you can make all values up to x, and you have a coin of value v, you can make all values up to x + v.
  • 2Sorting the coins allows us to efficiently determine the maximum consecutive values we can create.

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