Skip to content

Instantly share code, notes, and snippets.

@nichtemna
Created September 22, 2016 06:12
Show Gist options
  • Save nichtemna/a449401e0128d4afaf99db584a9de008 to your computer and use it in GitHub Desktop.
Save nichtemna/a449401e0128d4afaf99db584a9de008 to your computer and use it in GitHub Desktop.
Sum three numbers of array to get desired sum
/**
* Given an array, find there are 3 numbers have
when we add them the value will equals a specified sum
Example:
{1,4,6,10,20,21}
Sum=32, Result:true (1+10+21)
Sum=65, Result:false
6 32
1 4 6 10 20 21
*/
public class SumNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
int[] array = new int[n];
Set<Integer> set = new HashSet<>(n);
for (int i = 0; i < array.length; i++) {
int v = scanner.nextInt();
array[i] = v;
set.add(v);
}
List<String> res = new ArrayList<>();
for (int i = 0; i < array.length; i++) {
int v1 = m - array[i];
for (int j = i + 1; j < array.length; j++) {
int v2 = v1 - array[j];
if (v2 != array[i] && v2 != array[j] && set.contains(v2)) {
res.add(array[i] + " " + array[j] + " " + v2);
}
}
}
if (res.size() > 0) {
for (String re : res) {
System.out.println(re);
}
} else {
System.out.print("No");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment