I would solve this by dividing the array by half for each recursive call.
findMax(int[] data, int a, int b)
where a and b are the indices of the array.
The stopping condition is when b - a <= 1 , then they are neighbors, and max max (a, b);
Initial call:
findMax(int[] data, int 0, data.length -1);
This reduces the maximum recursion depth from N to log2 (N).
But the search effort is still O (N).
This will lead to
int findMax(int[] data, int a, int b) { if (b - a <= 1) { return Math.max(data[a], data[b]); } else { int mid = (a+b) /2; // this can overflow for values near Integer.Max: can be solved by a + (ba) / 2; int leftMax = findMax(a, mid); int rightMax = findMax(mid +1, b); return Math.max(leftMax, rightMax); } }
source share