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?
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);
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;
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With