Problem · Array

Minimum Absolute Sum

Learn this problem
EasyGoogleNEW GRADOA
See Google hiring insights

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[]) → int

Examples

Example 1

A = [1, 3, 2, 5]return = 1
Negating 5 changes the total from 11 to 1, which is optimal.

Example 2

A = [-4, 0, -3, 3]return = 2
Negating -3 produces [-4, 0, 3, 3] with sum 2, which is optimal.

Example 3

A = [4, -3, 5, -7]return = 1
The original sum is -1, and no sign flip improves its absolute value.

Example 4

A = [-15, 18, 1, -1, 10, -22]return = 7
The 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].

More Google problems

drafts saved locally
public int minAbsoluteSum(int[] A) {
  // write your code here
}
A[1, 3, 2, 5]
expected1
checking account