We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Minimum Elements to Add to Form a Given Sum

Number: 1911

Difficulty: Medium

Paid? No

Companies: X


Problem Description

Given an integer array nums and two integers limit and goal, find the minimum number of elements you need to add to nums so that its sum equals goal. All numbers (original and added) must satisfy abs(x) <= limit.


Key Insights

  • Compute the current sum of nums.
  • Determine the absolute difference between goal and the current sum.
  • Each added element can contribute at most limit (in absolute value) to reducing the difference.
  • The minimum number of elements needed is given by the ceiling of (difference / limit).

Space and Time Complexity

Time Complexity: O(n), where n is the length of nums (to compute the sum)
Space Complexity: O(1)


Solution

The solution involves first calculating the current sum of the array. Then, the difference (diff) between the goal and this sum is found and its absolute value is used. Since each inserted number can add at most limit to reduce this gap, the minimum number of elements is computed by taking the ceiling of diff divided by limit. This is efficiently done using the formula (diff + limit - 1) // limit, which handles the rounding up when diff is not exactly divisible by limit.


Code Solutions

def min_elements_to_add(nums, limit, goal):
    # Calculate the current sum of the array
    current_sum = sum(nums)
    # Compute the absolute difference to reach goal
    diff = abs(goal - current_sum)
    # Compute the minimum number of elements needed using ceiling division
    return (diff + limit - 1) // limit

# Example Test Cases
print(min_elements_to_add([1, -1, 1], 3, -4))  # Expected output: 2
print(min_elements_to_add([1, -10, 9, 1], 100, 0))  # Expected output: 1
← Back to All Questions