Skip to content

Commit e30f248

Browse files
committed
updated
1 parent a216cb8 commit e30f248

File tree

2 files changed

+44
-11
lines changed

2 files changed

+44
-11
lines changed
Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,41 @@
1-
package com.thealgorithms.dynamicprogramming;
1+
package com.example.algo;
22

33
public class Sum_Of_Subset {
44

55
public static void main(String[] args) {
66
int[] arr = {7, 3, 2, 5, 8};
77
int Key = 14;
88

9-
if (subsetSum(arr, arr.length - 1, Key)) {
9+
if (subsetSum(arr, arr.length, Key)) {
1010
System.out.print("Yes, that sum exists");
1111
} else {
1212
System.out.print("Nope, that number does not exist");
1313
}
1414
}
1515

16-
public static boolean subsetSum(int[] arr, int num, int Key) {
17-
if (Key == 0) {
18-
return true;
19-
}
20-
if (num < 0 || Key < 0) {
21-
return false;
16+
static boolean subsetSum(int[] arr, int n, int Key) {
17+
boolean[] prev = new boolean[Key + 1];
18+
19+
prev[0] = true;
20+
21+
if (arr[0] <= Key) {
22+
prev[arr[0]] = true;
2223
}
2324

24-
boolean include = subsetSum(arr, num - 1, Key - arr[num]);
25-
boolean exclude = subsetSum(arr, num - 1, Key);
25+
for (int ind = 1; ind < n; ind++) {
26+
boolean[] cur = new boolean[Key + 1];
27+
cur[0] = true;
28+
for (int target = 1; target <= Key; target++) {
29+
boolean notTaken = prev[target];
30+
boolean taken = false;
31+
if (arr[ind] <= target) {
32+
taken = prev[target - arr[ind]];
33+
}
34+
cur[target] = notTaken || taken;
35+
}
36+
prev = cur;
37+
}
2638

27-
return include || exclude;
39+
return prev[Key];
2840
}
2941
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package com.thealgorithms.sorts;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
5+
import org.junit.jupiter.api.Test;
6+
7+
class Sum_Of_SubsetTest {
8+
9+
@Test
10+
void basicCheck() {
11+
assertEquals(true, Sum_Of_Subset.subsetSum(new int[] {7, 3, 2, 5, 8}, 5, 14));
12+
13+
assertEquals(true, Sum_Of_Subset.subsetSum(new int[] {4, 3, 2, 1}, 4, 5));
14+
15+
assertEquals(false, Sum_Of_Subset.subsetSum(new int[] {2, 5, 1, 6, 7}, 5, 4));
16+
17+
assertEquals(false, Sum_Of_Subset.subsetSum(new int[] {1, 7, 2, 9, 10}, 5, 14));
18+
19+
assertEquals(true, Sum_Of_Subset.subsetSum(new int[] {1, 7, 2, 9, 10}, 5, 13));
20+
}
21+
}

0 commit comments

Comments
 (0)