Find the minimal absolute value of a sum of two elements.
- Difficulty Level: Medium
- Question URL: https://app.codility.com/programmers/lessons/15-caterpillar_method/min_abs_sum_of_two/
- Time Complexity:
Solution:
Solution to Codility's Minimal Absolute Sum Of Two problem which is from the Codility Lesson 15: Caterpillar method and, is solved in Java 8 with 100% performance and correctness scores. The goal here is to find the minimal absolute value of a sum of two elements. You can find the question of this MinAbsSumOfTwo problem in the Codility website.
package Codility.Lesson15;
import java.util.*;
public class MinAbsSumOfTwo {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a1 = { -8, 4, 5, -10, 3 };
int result2 = solution2(a1);
System.out.println(result2);
}
public static int solution(int[] A) {
int N = A.length;
Arrays.sort(A);
int tail = 0;
int head = N - 1;
int minAbsSum = Math.abs(A[tail] + A[head]);
while (tail <= head) {
int currentSum = A[tail] + A[head];
minAbsSum = Math.min(minAbsSum, Math.abs(currentSum));
// If the sum has become
// positive, we should know that the head can be moved left
if (currentSum <= 0)
tail++;
else
head--;
}
return minAbsSum;
}
}