I had a recursion interview question problem in Java,Need your help on this.
Write a **Java function** such that :: Given an array of ints, is it possible to divide the ints into two groups, so that the sum of the two groups is the same, with these constraints: all the values that are multiple of 5 must be in one group, and all the values that are a multiple of 3 (and not a multiple of 5) must be in the other. (No loops needed.)
split53({1,1}) → true
split53({1, 1, 1}) → false
split53({2, 4, 2}) → true
PS:This was a Interview Question for hewlett packard
The question can be easily reduced to following: given a set of integers
numbersand an integertarget, is it possible to find a subset ofnumberswith sum equal totarget?Let me know if transition needs clarification.
It can be solved with DP in
O(numbers.size * target)time. The idea is followingnumbers.sizeis0, the only reachable sum is0.numbers == {1, 3}, in this case sums{0, 1, 3, 4}are available. What if we add another element tonumbers,4? Now, all old sums can still be reached and some new ones too:{0 + 4, 1 + 4, 3 + 4, 4 + 4}. Thus, fornumbers == {1, 3, 4}, available sums are{0, 1, 3, 4, 5, 7, 8}.A working example (it doesn’t handle negative numbers, but you can easily fix that)
Run it
edit
I just noticed the “recursion” part of the requirement. Well, DP can be rewritten as recursion with memoization, if that’s the hard requirement. This would preserve runtime complexity.
edit 2
On groups. You have to assign elements divisible by 3 or 5 to respective groups before you proceed with the algorithm. Let’s say, sum of all elements is
s, sum of elements divisible by 3 iss3and sum of elements divisible by 5 but not 3 iss5. In this case, after you assigned those ‘special’ elements, you have to split the rest that sum in one group iss/2 - s3and in anothers/2 - s5.