-
Notifications
You must be signed in to change notification settings - Fork 1k
/
target_sum_triplets.java
54 lines (40 loc) · 1.1 KB
/
target_sum_triplets.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
50
51
52
53
54
import java.util.*;
class target_sum_triplets {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in); // input
int n = sc.nextInt(); // array size
int arr[] = new int[n];
for (int i = 0; i < n; i++){
arr[i] = sc.nextInt();// array elements
}
int target = sc.nextInt(); // target sum
Arrays.sort(arr);
for (int j = 0; j < n - 1; j++) {
int start = j + 1;
int end = n - 1;
while (start < end) {
if (arr[j] + arr[start] + arr[end] == target) {
System.out.println(arr[j] + ", " + arr[start] + " and " + arr[end]); // output
start++;
end--;
} else if (arr[j] + arr[start] + arr[end] < target)
start++;
else
end--;
}
}
}
}
/* Sample Input Output ->
Input
9
5 7 9 1 2 4 6 8 3
10
Output
1, 2 and 7
1, 3 and 6
1, 4 and 5
2, 3 and 5
Complexity Analysis
Time Complexity - O(n^2)
Space Complexity - O(1) */