forked from kakarot237/ml-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPair_with_given_sum.java
49 lines (44 loc) · 1.01 KB
/
Pair_with_given_sum.java
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
// Java program to check if given array
// has 2 elements whose sum is equal
// to the given value
import java.util.*;
class GFG {
// Function to check if array has 2 elements
// whose sum is equal to the given value
static boolean hasArrayTwoCandidates(
int A[],
int arr_size, int sum)
{
int l, r;
/* Sort the elements */
Arrays.sort(A);
/* Now look for the two candidates
in the sorted array*/
l = 0;
r = arr_size - 1;
while (l < r) {
if (A[l] + A[r] == sum)
return true;
else if (A[l] + A[r] < sum)
l++;
else // A[i] + A[j] > sum
r--;
}
return false;
}
// Driver code
public static void main(String args[])
{
int A[] = { 1, 4, 45, 6, 10, -8 };
int n = 16;
int arr_size = A.length;
// Function calling
if (hasArrayTwoCandidates(A, arr_size, n))
System.out.println("Array has two "
+ "elements with given sum");
else
System.out.println("Array doesn't have "
+ "two elements with given sum");
}
}
// This code is contributed by Pranjal rajput