https://codility.com/programmers/lessons/15-caterpillar_method/min_abs_sum_of_two/
Explanation: Coming soon
// you can use includes, for example: // #include <algorithm> // you can write to stdout for debugging purposes, e.g. // cout << "this is a debug message" << endl; #include <algorithm> #define DEBUG 0 #if DEBUG # define LOG(...) printf(__VA_ARGS__) #else # define LOG(...) #endif int solution(vector<int> &A) { // write your code in C++14 (g++ 6.2.0) //sort array in increasing order sort(A.begin(), A.end()); #if DEBUG LOG("sorted array: "); for (auto& a: A) { LOG("%d ", a); } LOG("\n"); #endif int left = 0; int right = A.size() - 1; //move two cursors closer to the diagonal (where absolute value of two sides are equal) int min_sum = 0x7fffffff; while (left <= right) { int sum = abs(A[left] + A[right]); min_sum = min(min_sum, sum); LOG("|A[%d] (%d) + A[%d](%d)| = %d --> min = %d\n", left, A[left], right, A[right], sum, min_sum); if (abs(A[left]) > abs(A[right])) left ++; else if (abs(A[left]) < abs(A[right])) right --; else break; } return min_sum; }