- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have an array called nums and two values limit and goal. The array is special because |nums[i]| <= limit for all i from 0 to size of array - 1. We have to find the minimum number of elements to be inserted to make the sum of the array same as goal. Array element should not exceed limit value.

So, if the input is like nums = [2,-2,2], limit = 3, goal = -4, then the output will be 2 because we can add two (-3)s, so that the array will be [2,-2,2,-3,-3]

To solve this, we will follow these steps −

s := sum of all elements present in nums

ab := |goal - s|

return the ceiling of (ab / limit)

Let us see the following implementation to get better understanding −

from math import ceil def solve(nums, limit, goal): s = sum(nums) ab = abs(goal - s) return ceil(ab / limit) nums = [2,-2,2] limit = 3 goal = -4 print(solve(nums, limit, goal))

[2,-2,2], 3, -4

2.0

- Related Questions & Answers
- Program to find minimum absolute sum difference in Python
- Print elements that can be added to form a given sum
- Program to find sum of elements in a given array in C++
- Python program to find sum of elements in list
- Program to find sum of unique elements in Python
- C/C++ Program to find the sum of elements in a given array
- Program to find minimum swaps required to make given anagram in python
- Program to find minimum required chances to form a string with K unique characters in Python
- Program to find minimum number of increments on subarrays to form a target array in Python
- Program to find minimum digits sum of deleted digits in Python
- Program to find minimum amplitude after deleting K elements in Python
- Program to find number of ways to form a target string given a dictionary in Python
- Program to find minimum element addition needed to get target sum in Python
- Program to find sum of all elements of a tree in Python
- Write a program to form a cumulative sum list in Python

Advertisements