Maintain a minimum and max difference as we scan the input array.

public static int maxDifference(int[] input){
    int maxDifference = Integer.MIN_VALUE, min = Integer.MAX_VALUE;
    for(int i = 0 ; i < input.length; i++){
      if(input[i]-min > maxDifference){
        maxDifference = input[i]-min;
      if(input[i] < min){
        min = input[i];
    return maxDifference == Integer.MIN_VALUE ? -1 : maxDifference;
  • 6
    \$\begingroup\$ Can you add an example? Also can you clarify the problem statement? \$\endgroup\$ – Exploring Mar 28 '18 at 16:03
  • \$\begingroup\$ I am voting to close as it remains unclear what OP is asking exactly. \$\endgroup\$ – dfhwze Sep 8 at 7:24

Your question statement isn't perfectly clear at the moment of writing this answer. Based on how I understood your implementation I'm going to assume you want to find the largest possible difference between 2 input values, which is the same as asking for the difference between the smallest and largest input value.

First of all there's a rather obvious bug in the code. See what happens for this input: [2,3,1]. The way I interpreted the question, this should return 2 (i.e. 3-1=2) but your code returns 1, can you tell why?

I prefer to start with validating input and handling edge cases. Assuming you want to return -1 if the input doesn't have at least 2 numbers you could start with this statement:

public static int maxDifference(int[] input){
    if(input.length < 2) return -1;

That way we're sure that from this point on there will be at least 2 numbers in the input.
Since we're going over all numbers in the input and don't care about the index we can use the foreach statement instead of a normal for: for(int next : input){.
As for the actual algorithm, it makes a lot more sense to me to just find the min and max values while going through the list and calculate the difference afterwards.

    for(int next : input){
        if(next > max){
            max = next;
        if(next < min){
            min = next;
    return max - min;

This also fixes the bug I mentioned previously.
The only thing left is initialising the min and max values. I strongly suggest doing this on separate lines though:

int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;

With this there is still one last bug to fix, but I'll leave that up to you (since code review is actually about reviewing working code, not fixing bugs). I'll give you 2 hints to spot the bug:

public static void main(String[] args) {
    int[] input = {Integer.MIN_VALUE, Integer.MAX_VALUE};

Why does that print -1? And what happens if you replace Integer.Min_Value with -2 for example?


Not the answer you're looking for? Browse other questions tagged or ask your own question.