Skip to content

Commit 89cd153

Browse files
Create SubsetSumToK.java
1 parent d2a9859 commit 89cd153

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import java.util.*;
2+
import java.io.*;
3+
public class SubsetSumToK {
4+
public static boolean subsetSumToK(int n, int k, int arr[]){
5+
boolean[][] dp = new boolean[n][k+1];
6+
7+
for(int i = 0; i<n; i++){
8+
dp[i][0] = true; // can form sum 0 by not picking the 'i'th element
9+
}
10+
11+
for(int j = 0; j<k+1; j++){
12+
if(j == arr[0]){
13+
dp[0][j] = true;
14+
}
15+
}
16+
17+
for(int i = 1; i<n; i++){
18+
for(int j = 1; j<k+1; j++){
19+
if(arr[i]<=k){
20+
dp[i][arr[i]] = true;
21+
}
22+
if(j>=arr[i]){
23+
dp[i][j] = dp[i-1][j] || dp[i-1][j-arr[i]]; // not pick or pick. pick -> check remaining sum
24+
}
25+
else{
26+
dp[i][j] = dp[i-1][j];
27+
}
28+
29+
}
30+
}
31+
32+
return dp[n-1][k];
33+
}
34+
}

0 commit comments

Comments
 (0)