Reputation: 41
So this is an unique question and I would appreciate any help.
The objective: To count and return an integer of 'distance' from min value to max value. The list is not sorted and should not be sorted. Min value might be before max or vise-verse. In a list of { 2, -5, -7, 8, 22, -10 } answer = 1 (the distance from -10 to 22) In a list of { 2, -5, -7, 8, 22, -6 } answer = 2 (the distance from -7 to 22)
Thank you for any help.
Upvotes: 1
Views: 4287
Reputation: 2102
Keep the indice while finding max
and min
:
int indMin = 0;
int indMax = 0;
double min = list[0];
double max = list[0];
for (int i =0; i<list.length;i++){
if(min>list[i]){
min=list[i];
indMin = i;
}
if(max<list[i]){
max = list[i];
indMax = i;
}
}
int distance = Math.abs(indMax - indMin);
Upvotes: 2
Reputation: 53819
Just keep track of the corresponding index:
double min = list[0];
int minIndex = 0;
double max = list[0];
int maxIndex = 0;
for (int i =1 ; i < list.length ; i++) {
if(min > list[i]){
min = list[i];
minIndex = i;
}
if(max < list[i]){
max = list[i];
maxIndex = i;
}
}
int res = Math.abs(minIndex - maxIndex);
Upvotes: 6