Minimum Absolute Sum
Problem statement
There is an array A consisting of N integers. Choose at most one element to multiply by -1 in order to obtain an array whose sum of elements is as close to 0 as possible. That is, find the sum with the minimum absolute value.
that, given an array A, returns the minimum absolute value of the sum of A that can be obtained.
Function
minAbsoluteSum(A: int[]) → intExamples
Example 1
A = [1, 3, 2, 5]return = 1Negating 5 changes the total from 11 to 1, which is optimal.
Example 2
A = [-4, 0, -3, 3]return = 2Negating -3 produces [-4, 0, 3, 3] with sum 2, which is optimal.
Example 3
A = [4, -3, 5, -7]return = 1The original sum is -1, and no sign flip improves its absolute value.
Example 4
A = [-15, 18, 1, -1, 10, -22]return = 7The original sum is -9. Negating -1 changes the sum to -7, so the minimum absolute value is 7.
Constraints
- N is an integer within the range [1..100,000];
- each element of array A is an integer within the range [-1,000..1,000].
Source note: The screenshots are independent source sightings of the same Google New Grad OA question.