Skip to content

Commit 207a109

Browse files
committed
Three Sum
1 parent 80a4c89 commit 207a109

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

src/easy/ThreeSum.java

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package easy;
2+
3+
/**
4+
* Have the function ThreeSum(arr) take the array of integers stored in arr,
5+
* and determine if any three distinct numbers (excluding the first element)
6+
* in the array can sum up to the first element in the array.
7+
* ---
8+
* For example: if arr is [8, 2, 1, 4, 10, 5, -1, -1] then
9+
* there are actually three sets of triplets
10+
* that sum to the number 8: [2, 1, 5], [4, 5, -1] and [10, -1, -1].
11+
* ---
12+
* Your program should return the string true
13+
* if 3 distinct elements sum to the first element,
14+
* otherwise your program should return the string false.
15+
* The input array will always contain at least 4 elements.
16+
*/
17+
public class ThreeSum {
18+
19+
/**
20+
* Three Sum function.
21+
*
22+
* @param arr input array
23+
* @return "true" if 3 distinct elements sum to the first element
24+
*/
25+
private static String threeSum(int[] arr) {
26+
for (int i = 1; i < arr.length; i++) {
27+
for (int j = i + 1; j < arr.length; j++) {
28+
for (int k = j + 1; k < arr.length; k++) {
29+
if (arr[i] + arr[j] + arr[k] == arr[0]) {
30+
return "true";
31+
}
32+
}
33+
}
34+
}
35+
return "false";
36+
}
37+
38+
/**
39+
* Entry point.
40+
*
41+
* @param args command line arguments
42+
*/
43+
public static void main(String[] args) {
44+
var result = threeSum(new int[]{8, 1, 2, 3, 4, 5, 7});
45+
System.out.println(result);
46+
}
47+
48+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy