Skip to content

Commit b9c5bc2

Browse files
author
Mang Yau
committed
Add SumOfPairs.
1 parent 3c68670 commit b9c5bc2

1 file changed

Lines changed: 43 additions & 0 deletions

File tree

SumOfPairs.java

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package javacodes;
2+
3+
/**
4+
* Given an array of ints A and an int m, find out if there exists
5+
* a pair of elements in A that add up to m in a relatively fast way.
6+
*/
7+
public class SumOfPairs {
8+
9+
public static boolean sumExists(int[] list, int m) {
10+
int[] differences = new int[list.length];
11+
12+
for (int i = 0; i < list.length; i++) {
13+
int curr = list[i];
14+
15+
// ignore the trivial case where m is an element of the list.
16+
if (curr == m) {
17+
continue;
18+
}
19+
20+
int diff = m - curr;
21+
22+
for (int j = 0; j <= i; j++) {
23+
int currDiff = differences[j];
24+
25+
if (currDiff == diff || currDiff == curr) {
26+
27+
System.out.println("A pair is " + curr + " and " + diff + "\n");
28+
return true;
29+
}
30+
}
31+
32+
differences[i] = diff;
33+
}
34+
35+
return false;
36+
}
37+
38+
public static void main(String[] args) {
39+
int[] l = {1, 8, 10, 3, 2, 6};
40+
41+
System.out.println(sumExists(l, 8));
42+
}
43+
}

0 commit comments

Comments
 (0)