Apologies for the ambiguous title, I could not think of something more specific.
In order to get better at solving problems recursively, I have been tackling the questions posted on CodingBat. My question is related to a variation of the following problem.
The original problem is:
Given an array of ints, compute recursively if the array contains somewhere a value followed in the array by that value times 10. We'll use the convention of considering only the part of the array that begins at the given index. In this way, a recursive call can pass index+1 to move down the array. The initial call will pass in index as 0.
- array220({1, 2, 20}, 0) → true
- array220({3, 30}, 0) → true
- array220({3}, 0) → false
My solution to this problem is:
public boolean array220(int[] nums, int index) {
if (index >= nums.length-1) return false;
if (nums[index+1] == nums[index] * 10) return true;
return array220(nums, ++index);
}
However, in order to challenge myself, I was wondering how I would go about solving the following variation of this problem that I conceived:
Given an array of ints, compute recursively if the array contains somewhere a value that is 10 times larger than any other value. We'll use the convention of considering only the part of the array that begins at the given index. In this way, a recursive call can pass index+1 to move down the array. The initial call will pass in index as 0.
For example:
- array220({1, 2, 10}, 0) → true
- array220({3, 2, 9, 38, 20}, 0) → true
- array220({3}, 0) → false
So basically, the difference with the original problem is that the values may not necessarily be adjacent to one another (see examples above).
How would I go about doing this recursively? I would appreciate some pointers.
I do not want to change the method signature or use global variables.