The source of the problem is here.
Given an array of integer elements, return the maximum difference of any pair of numbers such that the larger number of the pair occurs at a higher index than the smaller.
Here is my implementation in Java.
package algo.mindiff;
public class Main {
// http://www.careercup.com/question?id=5185822661804032
public static void main(String[] args) {
System.out.println(minDiff(new int[] { 10, 1, 12, 3, 4, 28, 1 }));
}
private static int minDiff(int[] array) {
int diff = 0;
int result = 0;
for (int i = 0; i < array.length;) {
int maxIndex = maxIndex(array, i);
int minIndex = minIndex(array, i, maxIndex);
diff = array[maxIndex] - array[minIndex];
if (result < diff)
result = diff;
i = maxIndex + 1;
}
return result;
}
private static int minIndex(int[] array, int start, int end) {
int min = start;
for (int i = start + 1; i < end; i++) {
if (array[i] < array[min]) {
min = i;
}
}
return min;
}
private static int maxIndex(int[] array, int start) {
int max = start;
for (int i = start + 1; i < array.length; i++) {
if (array[i] >= array[max]) {
max = i;
}
}
return max;
}
}
And here is a brief summary of my algorithm:
- I find the maximum element in the given array. Its index is
maxIndex
. - Then I find the minimum element within the range
[0, maxIndex)
. Its index isminIndex
. - If the difference
result
I calculated last time is less than the differencediff
betweenarray[maxIndex]
andarray[minIndex]
, I'll just assign the new value toresult
. - I do steps 1 - 3 for the other elements of the array starting with
maxIndex + 1
.
If my algorithm doesn't work on any input data you might have in mind, please let me know.