-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpossibleSum.java
More file actions
58 lines (49 loc) · 1.15 KB
/
possibleSum.java
File metadata and controls
58 lines (49 loc) · 1.15 KB
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
55
56
57
58
import java.util.Arrays;
import java.util.Scanner;
/*ACTest: 62.5%*/
public class possibleSum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int numOfInput = sc.nextInt();
int[] arrayA = new int[numOfInput];
for(int i=0; i<numOfInput; i++){
arrayA[i] = sc.nextInt();
}
int target = sc.nextInt();
possibleSum sol = new possibleSum();
System.out.println(sol.findPossibleSum(arrayA, target));
}
public boolean findPossibleSum(int[] arrayA, int target){
//Sort the array
Arrays.sort(arrayA);
int sum = 0;
for(int i=arrayA.length-1; i>=0; i--){
if(target < arrayA[i]){
continue;
}else{
for(int j=i; j>=0; j--){
sum += arrayA[j];
if(sum == target){
return true;
}else if(sum > target){
//test negative number
for(int k=0; k<j; k++){
if(arrayA[k] < 0){
sum += arrayA[k];
if(sum == target){
return true;
}
}else{
break;
}
}
return false;
}else{
continue;
}
}
}
}
return false;
}
}