Problem solving with programming: Number of pairs with sum less than or equal to given value
Given an array of numbers, Count the number of pairs with sum less than or equal to K
A[0] A[1] A[2]... A[N]
b--> <--e
Considering the above example
Given an array of numbers, Count the number of pairs with sum less than or equal to K
- First sort the array in ascending order.
- Take two indices one(b) pointing to the start of the array, and the other(e) pointing to the last element of the array.
- If A[b]+A[e] <= K
- All the elements between [b+1,e] also satisfy the given property.
- Increment b and decrement e and repeat step 3
- Otherwise decrement e
- Repeat step 3 until b and e meet each other.
A[0] A[1] A[2]... A[N]
b--> <--e
Considering the above example
{1, 3, 5, 6, 12} let b = 0, e = 3 and K = 10
1 3 5 6 12
b e
If we add 6 or 5 or 3 to 1, the sum is less than 10. At this point, we can increment the pair count in one shot.
1 3 5 6 12
b e
If we add 6 or 5 or 3 to 1, the sum is less than 10. At this point, we can increment the pair count in one shot.
Read full article from Problem solving with programming: Number of pairs with sum less than or equal to given valuepublic static int getPairsWithSumOrLess(int[] array, int sum){Arrays.sort(array);int pairCount = 0;for( int i = 0, j = array.length-1; i < j; ){if( array[i]+array[j] <= sum ){pairCount += j-i;i++;j--;}else{j--;}}return pairCount;}