Last Updated: 10 Apr, 2021

Minimum Numbers Required

Easy
Asked in companies
WalmartFlipkart limited

Problem statement

You are given an array, 'ARR', consisting of ‘N’ integers. You are also given two other integers, ‘SUM’ and ‘MAXVAL’. The elements of this array follow a special property that the absolute value of each element is not more than ‘MAXVAL’.

Your task is to determine the minimum number of integers required to be added into the array such that the sum of all the elements of the array becomes equal to ‘SUM’.

Note:
All the new numbers being added to the array must follow the original property of the array.
Input Format:
The first line contains an integer ‘T’, which denotes the number of test cases to be run. Then, the T test cases follow. 

The first line of each test case contains a single integer ‘N’.

The second line of each test case contains two space-separated integers, ‘SUM’ and ‘MAXVAL’, denoting the required sum of the array elements, and the maximum absolute value of each element in the array.

The third and the last line of each test case contains ‘N’ space-separated integers, denoting the elements of the array, ARR. 
Output Format:
For each test case, print in a separate line a single integer, denoting the minimum number of integers required to be added into the array.

Output for each test case will be printed in a separate line.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 10
1 <= N <= 10^6
-10^9 <= SUM <= 10^9
1 <= MAXVAL <= 10^9
-MAXVAL <= NUMS[i] <= MAXVAL

Where 'T' denotes the number of test cases, ‘N’ represents the original number of elements present in the array, ‘SUM’ represents the required sum of all the elements in the array, ‘MAXVAL’ represents the maximum absolute value of any element in the array and ARR[i] represents the value of the elements in the array.

Time Limit: 1sec

Approaches

01 Approach

 

The approach is to find the sum of all the original elements of the array. Now, we can easily find the sum required to be added into the array. So we keep adding the maximum allowed absolute value of a number that can be added into the array as long as the sum of the array does not exceed the required value of ‘SUM’. Now, we can simply add an integer equal to the difference between the value of ‘SUM’ and the current sum of all the elements in the array.

 

 

Algorithm:

 

  1. Initialize a variable, say currentSum = 0. This will be used to store the sum of the array elements.
  2. For every num in ARR, add it to currentSum.
  3. Find the absolute difference between sum and currentSum and store it as requiredSum.
  4. Define numsRequired = requiredSum / maxVal.
  5. If requiredSum % maxVal > 0, we need to increase the value of numsRequired by 1, because we need one more integer to make the sum equal to sum.
  6. Return numsRequired.