-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathCountOfPairsWithGivenSum.java
More file actions
56 lines (43 loc) · 1005 Bytes
/
CountOfPairsWithGivenSum.java
File metadata and controls
56 lines (43 loc) · 1005 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
Count of pairs with the given sum
Given a sorted array of distinct integers A and an integer B, find and return how many pair of integers ( A[i], A[j] ) such that i != j have sum equal to B.
Input Format
The first argument given is the integer array A.
The second argument given is integer B.
Output Format
Return the number of pairs for which sum is equal to B.
Constraints
1 <= length of the array <= 100000
1 <= A[i] <= 10^9
1 <= B <= 10^9
For Example
Input 1:
A = [1, 2, 3, 4, 5]
B = 5
Output 1:
2
Input 2:
A = [5, 10, 20, 100, 105]
B = 110
Output 2:
2
*/
public class Solution {
public int solve(int[] A, int B) {
int i=0, j=A.length-1, count=0;
while(i<j){
if(A[i]+A[j]==B){
i++;
j--;
count++;
}
else if(A[i]+A[j]>B){
j--;
}
else{
i++;
}
}
return count;
}
}