Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the largest possible difference in an array with the smaller integer occurring earlier

Tags:

java

algorithm

This is an interview question:

Find the largest possible difference in an array of integers, such that the smaller integer occurs earlier in the array.

Constraint: Numbers are not unique. The range is Integer range of java. (or any other language)

Example:

input 1: {1, 100, 2, 105, -10, 30, 100}

The largest difference is between -10 and 100 -> 110 (here -10 is at the 5th index and 100 is at 7th index)

input 2: {1, 100, 2, 105, -10, 30, 80}

The largest difference is between 1 and 105 -> 104 (here 1 is at the 1st index and 105 is at 4th index)

Possible Solution:

One approach is check for all possible differences and keep a track of the biggest difference found till now O(n^2) complexity.

can this be done in better than O(n^2) time?

like image 919
Vivek Avatar asked Aug 08 '12 06:08

Vivek


3 Answers

Dhandeep's algoritm is good and Vivek's translation of the code to Java works! Also, we can also scan the array normally and not in reverse:

int seed[] = {1, 100, 2, 105, -10, 30, 100};
int maxDiff=Integer.MIN_VALUE, minNumber = Integer.MAX_VALUE;

for (int i = 0; i < seed.length ; i++){
    if(minNumber > seed[i]) 
       minNumber = seed[i];

    maxDiff = Math.max(maxDiff, (seed[i]-minNumber));
}
System.out.println(maxDiff);
like image 78
Nir Alfasi Avatar answered Oct 25 '22 20:10

Nir Alfasi


Start from the last element and move backwards. keep in memory the largest element occurred till now. for each element subtract from the max and store at the respective position.

Also, you can keep an element to store the max difference and give the output straight away. O(n) time, O(1) space.

int max = INT_MIN;
int maxdiff = 0;

for (i = sizeof(arr) / sizeof(int) - 1; i >= 0; i--) {
  if (max < arr[i]) {
    max = arr[i];
  }
  int diff = max - arr[i];
  if (maxdiff < diff) {
    maxdiff = diff;
  }
}

print maxdiff;
like image 26
Dhandeep Jain Avatar answered Oct 25 '22 18:10

Dhandeep Jain


Thanks @Dhandeep Jain for the answer. There is the java version:

//int seed[] = {1, 100, 2, 105, -10, 30, 100};
        int seed[] = {1, 100, 2, 105, -10, 30, 80};
        int maxDiff=Integer.MIN_VALUE, maxNumber = Integer.MIN_VALUE;

        for (int i = (seed.length-1); i >=0 ; i--){
            if(maxNumber < seed[i]) 
                maxNumber = seed[i];

            maxDiff = Math.max(maxDiff, (maxNumber - seed[i]));
        }
        System.out.println(maxDiff);
like image 24
Vivek Avatar answered Oct 25 '22 18:10

Vivek