i have made a java program for following problem statement -
"Dividing a set of numbers in to two sets such that sum of elements in each set must be equal "
input: array of integers
output:
"Yes"-if set can be divided in to two equal sum,
"No" -if can not be divided in to two equal sum,
"Invalid" -if integer array contains any other type of Integers(excepting positive integers)
and i have submitted the code to an online compiler and the code i have written has passed 8 test cases out of 10.i tried hard but i couldnt succeed finding those two test cases which failed . what are those two test-cases which failed ? here's the code -
public class CandidateCode
{
public static String partition(int[] arr) {
int sum = getSum(arr);
int half = sum / 2;
int out = 0;
int i = 0;
boolean flag = false;
if (hasZero(arr)) {
return "Invalid";
}
if (sum % 2 != 0) {
return "No";
}
if (arr.length == 2) {
if (arr[0] == arr[1]) {
return "Yes";
}
return "No";
}
else {
while (i < arr.length) {
if (arr[i] < half)
out += arr[i];
if (out == half) {
flag = true;
break;
}
i++;
}
}
if (flag)
return "Yes";
else
return "No";
}
public static int getSum(int[] arr) {
int result = 0;
for (int i = 0; i < arr.length; i++) {
result += arr[i];
}
return result;
}
public static boolean hasZero(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] <= 0) {
return true;
}
}
return false;
}
}
Aucun commentaire:
Enregistrer un commentaire