Search

Minimum Elements to Add to Form a Given Sum

Updated: Mar 24, 2021

You are given an integer array nums and two integers limit and goal. The array nums has an interesting property that abs(nums[i]) <= limit.


Return the minimum number of elements you need to add to make the sum of the array equal to goal. The array must maintain its property that abs(nums[i]) <= limit.


Note that abs(x) equals x if x >= 0, and -x otherwise.


Example 1:

Input: nums = [1,-1,1], limit = 3, goal = -4
Output: 2
Explanation: You can add -2 and -3, then the sum of the array will be 1 - 1 + 1 - 2 - 3 = -4.

Example 2:

Input: nums = [1,-10,9,1], limit = 100, goal = 0
Output: 1

Constraints:

  • 1 <= nums.length <= 105

  • 1 <= limit <= 106

  • -limit <= nums[i] <= limit

  • -109 <= goal <= 109

Solution:

class Solution {
    public int minElements(int[] nums, int limit, int goal) {
       long sum = 0;
        for(int num:nums)
        {
            sum+=num;
        }
        long diff = Math.abs(sum-goal);
        return (int)(diff/limit)+(diff%limit>0?1:0);
    }
}

12 views0 comments

Recent Posts

See All

A string s is called good if there are no two different characters in s that have the same frequency. Given a string s, return the minimum number of characters you need to delete to make s good. The f

The numeric value of a lowercase character is defined as its position (1-indexed) in the alphabet, so the numeric value of a is 1, the numeric value of b is 2, the numeric value of c is 3, and so on.