Created
June 12, 2022 14:51
-
-
Save hrit-ikkumar/8f2ed2f070b29d84f8c25604a84ee3df to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
// DO NOT MODIFY THE LIST. IT IS READ ONLY | |
public int solve(final List<Integer> A) { | |
// calculate sum of A | |
int sum = 0; | |
int n = A.size(); | |
for(int x: A) sum+= x; | |
sum/=2; | |
// dp table for (N+1) X (SUM + 1) | |
int dp_table[][] = new int[n+1][sum+1]; | |
// set int max value for sum more than 0 when we don't have any element | |
for(int i=1; i<= sum;i++)dp_table[0][i] = Integer.MAX_VALUE; | |
for(int i=1;i<= n;i++) { | |
for(int j=1;j<= sum;j++) { | |
// set the without using element choice | |
dp_table[i][j] = dp_table[i-1][j]; | |
// when we select the element | |
if(A.get(i-1) <= j && dp_table[i-1][j - A.get(i-1)] != Integer.MAX_VALUE) { | |
dp_table[i][j] = Math.min(dp_table[i][j], dp_table[i-1][j-A.get(i-1)] + 1); | |
} | |
} | |
} | |
// find the element which can made by suming element in array | |
for(int i=sum;i>=0;i--) { | |
if(dp_table[A.size()][i] != Integer.MAX_VALUE) { | |
return dp_table[A.size()][i]; | |
} | |
} | |
return 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment