I am working on some kata but I cannot pass all the test cases.
So the situation is:
Given any array, such as this array: int[] a = {2, 3, 10, 2, 4, 8, 1}
, find the max difference pair in the array, in the meantime make sure the larger value is at the higher index than the lower value.
In this example: 10
is the largest element, 1
is the smallest, since 10
is at index 2
, 1
is at index 6
, so it does not count because the larger pair is at a lower index. So the correct answer is a[0]
, and a[2]
, max different is 10-2
.
Other requirement is array size N
is between 1
and 1_000_000
, any given a[i]
is between -1_000_000
and 1_000_000
I wrote code like this:
static int maxDifference(int[] a) {
//test array size
if (a.length < 1 || a.length > 1_000_000) return -1;
int[] oldArr = Arrays.copyOf(a, a.length);
Arrays.sort(a);
int max = a[a.length - 1];
if (max > 1_000_000 || a[0] < -1_000_000) return -1;
int min = max;
for (int i = 0; i < oldArr.length; i++) {
if (oldArr[i] < max) {
min = Math.min(min, oldArr[i]);
}
if (oldArr[i] == max) break;
}
int result = min == max ? -1 : max - min;
return result;
}
My logic is pretty much make a copy of the array and then sort the array, then loop it though, keep a pointer for max and min values, then get the result.
What is troubling me is I only know there are some test cases I didn't pass, but no hints on why it didn't pass. Can anyone give me some advise and what I may missing in this helper method?
Approach: The maximum absolute difference in the array will always be the absolute difference between the minimum and the maximum element from the array.
Approach: Initially, check the first number which is different from a[0] starting from the end, store the difference of their index as ind1. Also, check for the first number which is different from a[n – 1] from the beginning, store the difference of their index as ind2. The answer will be max(ind1, ind2).
You can use array#map . For the first index value subtract from 0 and for other indexes, subtract from the previous number. Save this answer.
Basically you need to keep track of the minimum value found so far and the maximum diff found so far:
static int maxDifference(int[] a) {
int minimum, diff = -1;
if(a.length == 0) {
return -1;
}
minimum = a[0];
for (int i = 1; i < a.length; i++) {
diff = Math.max(diff, a[i] - minimum);
minimum = Math.min(minimum, a[i]);
}
return diff;
// depending on interpretation of requirements, above line might be wrong
// Instead, use:
// return diff > 0 ? diff : -1;
}
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