HiveBrain v1.2.0
Get Started
← Back to all entries
gotchajavaMinor

Find the max. difference between two array elements a[j] and a[i] such that j > i

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
suchtheelementsarraydifferencetwobetweenmaxthatfind

Problem

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[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 is minIndex.



  • If the difference result I calculated last time is less than the difference diff between array[maxIndex] and array[minIndex], I'll just assign the new value to result.



  • 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.

Solution

The algorithm you're using does a bunch of superfluous work. It would be much more efficient to concentrate on tracking the maximum difference that conforms to the specification than where you are in the array.

Setting the maxIndex the first time through your main loop isn't really setting any meaningful limit for you, because you also need to check to see if there are any other number combinations that have a higher difference than just the array maximum. In fact, you don't need to know what the highest value is at all or it's position in the array. The highest difference already assumes both of these, because when you set the greatest difference it is calculated based on the lowest value up to the current point in the array.

The idea of limiting the minimum check to the position of the previous high is well intentioned, but why not just run through the array once and keep track of everything at the same time?

The pseudo-code is much simpler:

  • Set the first value in the array to your low value.



  • Loop through the


array.

  • If the current element minus the low value is higher than the


maximum difference found, update the maximum difference.

  • If the current element is lower than the previous low, update the previous


low value.

  • Return the maximum difference when you hit the end of the array.

Context

StackExchange Code Review Q#85857, answer score: 3

Revisions (0)

No revisions yet.