Wednesday, January 25, 2012

Find triplet such that (a+b+c) is closest to 0


Find triplet <a,b,c> such that (a+b+c) is closest to 0.


Code output:


Array values are: 
-12 -7 -4 2 3 5 9 10 15 16 
We found a triplet that sums to zero!!
Triplet is: 
-12, -4, 16


Array values are: 
-29 -9 -4 2 3 9 10 15 16 49 
Triplet whose sum is closest to zero by: 1
Triplet is: 
-4, 2, 3


Approach:
1. For every A[i], have 2 pointers in the array say j at the A[i+1] and k at A[n-1] and a min variable which will store how far the (a+b+c) sum is from zero.
2. Check the expression (A[i]+A[j]+A[k] == 0), if false then do ++j or --k depending on (A[i] < A[j]+A[k]) or (A[i] > A[j]+A[k]).
Also check if (A[i]+A[j]+A[k]) < min, if yes then replace the min value with (A[i]+A[j]+A[k]).
3. If true, we have found an exact match for triplet that sums to zero, break the loop.
4. At (2) and (3) points we store the triplet in fa, fb, fc - ie final a, final b and final c.


total time complexity: O(n^2)


No comments:

Post a Comment