Possible Duplicate:
Java : Summation ofmultiples of 5in a group to a given target
Hi SO People,
I’m struggling to get the below problem working with no approach in right direction.
Write a java function such that given an array of ints, is it possible to choose a group of some of the ints, such that the group sums to the given target with these additional constraints: all multiples of 5 in the array must be included in the group. If the value immediately following a multiple of 5 is 1, it must not be chosen.
- groupSum5(0, {2, 5, 10, 4}, 19) → true
- groupSum5(0, {2, 5, 10, 4}, 17) → true
- groupSum5(0, {2, 5, 10, 4}, 12) → false
- groupSum5(0, {3, 5, 1}, 5) → true
- groupSum5(0, {3, 5, 1}, 4) → false
The function siganture is public boolean groupSum5(int start, int[] nums, int target)
I have written the partial code but there are failing test cases for the same.
public boolean groupSum5(int start, int[] nums, int target) {
start = 0;
boolean flag = false;
for(int i=0;i<nums.length;i++){
if(nums[i]%5==0){
start+=nums[i];
}else if((start != target) && (start%5==0)){
start+=nums[i];
}else if(start == target){
flag = true;
return flag;
}else if((nums[i]%5==0) && (nums[i+1]==1)){
continue;
}
}
return flag;
}
All the test cases are failing even after writing this code.
Im struggling to get this rite for a long time.
EDIT for DIANTE:Could you provide me with the code fix since i have tried this much and i dont know how to proceed
here’s a solution, but see discussion after:
Associated test:
BUT, your signature parameter
startsuggest something with recursion. In a first step, you could remove from the array of ints:then call you method with start and the new array of int.
In the method, you need to:
Example: { 2, 5, 10, 4 }, target = 19
sum of multiple of 5: 5+10 = 15, no 1 preceded by 5 => new array { 2, 4 }
first call:
method(15, {2, 4}, 19)second call (r1):
method(15+2, {4}, 19)third call (r11):
method(15+2+4, {}, 19)second call (r2):
method(15+4, {2}, 19)we are back in the first call with
r1 = r11 = falseandr2 = true=>return false OR true = true, ENDYou can see that
Sets.powerSetis equivalent to the recursive call r(k)