## Interview Question

**Country:**United States

```
rivate static int[] getClosestSum(int target[], int sum, int diff, int index, int[] pair, int nextindex) {
// int [] array = { 1, 5, 3, 6, 2};
int[] nextPair = null;
if (target.length == index || target.length == nextindex) {
return pair;
}
nextPair = getClosestSum(target, sum, diff, index, pair, nextindex + 1);
if (target[index] + target[nextindex] == sum) {
int currentMin = target[index] - target[nextindex];
int prevMin = pair[0] - pair[1];
if (currentMin == Math.min(currentMin, prevMin) && currentMin >= 0) {
pair[0] = target[index];
pair[1] = target[nextindex];
}
}
// nextPair = getClosestSum(target, sum, diff, index+1, pair,
// nextindex+1);
return pair;
}
public static void main(String[] args) {
int[] array = { 1, 5, 3, 6, 2 };
int[] pair = { Integer.MAX_VALUE, 0 };
int[] result = null;
int index = 0;
for (int num : array) {
result = getClosestSum(array, 8, 0, index++, pair, 1);
}
System.out.println(result);
// given 8 = {5,3} and not {6,2}
}
```

```
rivate static int[] getClosestSum(int target[], int sum, int diff, int index, int[] pair, int nextindex) {
// int [] array = { 1, 5, 3, 6, 2};
int[] nextPair = null;
if (target.length == index || target.length == nextindex) {
return pair;
}
nextPair = getClosestSum(target, sum, diff, index, pair, nextindex + 1);
if (target[index] + target[nextindex] == sum) {
int currentMin = target[index] - target[nextindex];
int prevMin = pair[0] - pair[1];
if (currentMin == Math.min(currentMin, prevMin) && currentMin >= 0) {
pair[0] = target[index];
pair[1] = target[nextindex];
}
}
// nextPair = getClosestSum(target, sum, diff, index+1, pair,
// nextindex+1);
return pair;
}
public static void main(String[] args) {
int[] array = { 1, 5, 3, 6, 2 };
int[] pair = { Integer.MAX_VALUE, 0 };
int[] result = null;
int index = 0;
for (int num : array) {
result = getClosestSum(array, 8, 0, index++, pair, 1);
}
System.out.println(result);
// given 8 = {5,3} and not {6,2}
}
```

In ZoomBA:

```
/*
To solve this :
1. Create a map with value as key, and index as value.
2. Iterate the list with testing sum (S) S - item is in the map or not.
2.1. If it is,
2.1.1 and the difference in position is
smaller than previous min store as min
2.1.2 Ignore
2.2. If it is not continue to [2]
*/
def solution( arr, S ){
// a map of key ( item ) -> item index
map = dict(arr) -> { [ $.o , $.i ] }
min = [ -1,-1, num('inf') ] // store +infinity as minimum
fold ( arr , min ) -> {
diff = S - $.o
if( diff @ map && map[diff] != $.i && $.p.2 > #|$.i - map[diff]| ){
$.p = [ $.i , map[diff] , #|$.i - map[diff]| ]
}
$.p // returns
}
}
arr = [1,4,5,3,6,4,2]
#(i,j) = solution( arr , 8 )
printf( '%d,%d\n', arr[i], arr[j] )
```

- srterpe December 06, 2016