Reputation: 675
I'm learning Java and I trying to construct a method for my homework. It takes as argument an Array
and returns the difference between its elements (as absolute value).
For example: array {7,8,5,7,2}
the difference between elements 0 and 1 is 1 (=7−8)
the difference between elements 1 and 2 is 3 (=8−5)
the difference between elements 2 and 3 is 2 (=5-7)
the difference between elements 3 and 4 is 5 (=7−2)
the difference between elements 4 and 0 is 5 (=2-7)
If there are multiple candidates the method will return the one with the greatest index. In this example, the last one. If the array
is empty, then the method must return −1
.
I have some problems in my code (as you can see) and the biggest one is that my method returns only the last diff
and not the biggest one with the higher index. Can someone help me? I'm not figuring out how to solve this problem.
public static int MaxDiff(int[] array){
int diff = 0;
if (array.length == 0){ // Checks for empty array
return -1;
}
for (int i = 0; i <= array.length; ++i){
if(i == array.length){
diff = Math.abs(array[i] - array[0]);
} else {
diff = Math.abs(array[i] - array[i+1]); // Mistake. Can be
// bigger than array
}
}
return diff;
}
Upvotes: 2
Views: 9204
Reputation: 11575
You have to set diff only if it is bigger than it already is.
int newDiff;
if(i == array.length - 1){
newDiff = Math.abs(array[i] - array[0]);
} else {
newDiff = Math.abs(array[i] - array[i+1]);
}
if(newDiff > diff)
diff = newDiff;
Also as @singhakash says the index of the last element of an array of size n
is n - 1
, not n
.
Upvotes: 0
Reputation: 493
I have changed a little and then your code works correctly.
public static int MaxDiff(int[] array){
int diff = 0;
if (array.length == 0){
return -1;
}
int max = 0;
for (int i = 0; i < array.length-1; ++i){
diff = Math.abs(array[i] - array[i+1]);
if(max < diff)
max = diff;
}
return max;
}
Upvotes: 2
Reputation: 6404
Create one instance variable maxDiff and update if you find diff greater than current computation diff in the loop. like
maxDiff = diff > maxDiff ? diff : maxDiff;
Finally return the maxDiff;
public static int MaxDiff(int[] array){
//create a variable to hold maxDiff;
int maxDiff = 0;
int diff = 0;
if (array.length == 0){ // Checks for empty array
return -1;
}
//Change from <= to < (otherwise you will get ArrayIndexOutOfBound exception
for (int i = 0; i < array.length; ++i){
if(i == array.length -1){
diff = Math.abs(array[i] - array[0]);
} else {
diff = Math.abs(array[i] - array[i+1]); // Mistake. Can be
// bigger than array
}
//check for max
maxDiff = diff > maxDiff ? diff : maxDiff;
}
return maxDiff;
}
Upvotes: 0