I am developing an algorithm for finding the number of tuples whose sum is equal to or less than a given number. I know other ways to solve it using LinkedList, so I am not looking for this solution. I just want to go through the array and count possible matches that satisfy the relation. I have come up so far
public static int numberOfPairs(int[] a, int k ){
int len = a.length;
if (len == 0){
return -1;
}
Arrays.sort(a);
int count = 0, left = 0, right = len -1;
while( left < right ){
if ( a[left] + a[right] <= k ){
count++;
if ( a[left] + a[left+1] <= k) {
count ++;
}
while (a[left] == a[left+1] && left < len-1 ){
left++;
}
if ( a[right] + a[right-1] <= k) {
count ++;
}
while ( a[right] == a[right-1] && right >1 ){
right-- ;
}
}
left++;
right--;
}
return count;
}
This does not provide the correct solution, say if I pass in an array and a number as follows,
int [] arr = { 3, 3, -1, 4, 2,5, 5, 1};
System.out.println(numberOfPairs(arr, 8));
The correct decision will consist of 15 pairs:
{
{-1,1}, {-1,2} , {3,-1}, {-1,4 }, {-1,5},
{2,1},{3,1 },{4,1}, { 5,1},
{3,2 },{4,2}, {2,5 },
{3,4 } , {3,5 },
{3,3}
}
How can I improve my code? Thank you
Note. Another way that I solve using LinkedList is as follows:
public static int numberOfPairs10(int[] arr, int sum){
List<Integer> li = new ArrayList<Integer>();
List<Integer> lj;
int count = 0;
for ( int i =0; i < arr.length -1 ; i++){
if (li.contains(arr[i]) )
continue;
lj = new ArrayList<Integer>();
for (int j = i+1; j < arr.length; j++){
if (lj.contains(arr[j]))
continue;
if ( arr[i]+ arr[j] == sum){
count++;
lj.add(arr[j]);
}
}
li.add(arr[i]);
}
return count;
}