deepakl.2000 - 1 year ago 77
Java Question

# Find the heights between the distances of a walking trail

We have an array of heights, representing the altitude along a walking trail. Given

`start`
/
`end`
indexes into the array, return the sum of the changes for a walk beginning at the
`start`
index and ending at the
`end`
index. For example, with the heights
`{5, 3, 6, 7, 2}`
and
`start=2`
,
`end=4`
yields a sum of
`1 + 5 = 6`
. The start end end index will both be valid indexes into the array with
`start <= end`
.

``````sumHeights({5, 3, 6, 7, 2}, 2, 4) => 6
sumHeights({5, 3, 6, 7, 2}, 0, 1) => 2
sumHeights({5, 3, 6, 7, 2}, 0, 4) => 11
``````

i'm struggling to get this right, i have tried a part of this but im confused and im getting
`ArrayIndexOutOfBoundsException`
.

`````` public int sumHeights(int[] heights, int start, int end) {

int total =0;
int difference =0;
for(int i=start;i<=end;i++){
if(heights[i] > heights[i++]){
difference =heights[i] - heights[i++];
}else if(heights[i++] > heights[i]){
difference =heights[i++] - heights[i];
}
total+=difference;
}
}
``````

You increment i in your loop thus possibly going out of bounds:

``````for(int i=start;i<=end;i++){      // here i might be last valid index, i.e. 4 in your example
if(heights[i] > heights[i++]){    //here i might be 5 (because of i++), i.e. you'd get the ArrayIndexOutOfBoundsException
difference =heights[i] - heights[i++]; //here i might be 6 (because of another i++), i.e. you'd get the ArrayIndexOutOfBoundsException
}else if(heights[i++] > heights[i]){     //here i might be 5, i.e. you'd get the ArrayIndexOutOfBoundsException
difference =heights[i++] - heights[i];
}
total+=difference;
}
``````

To fix it, use:

``````for(int i=start;i<end;i++){
int next = i + 1;
if(heights[i] > heights[next]){
difference =heights[i] - heights[next]; //assuming you mean next = i + 1 here and not next = i + 2 like in your code
}else if(heights[next] > heights[i]){
difference =heights[next] - heights[i];
}
else {
difference = 0; //due to public demand I'll help you with this, too
}

total+=difference;
}
``````

Edit: you could also make the loop much simpler:

``````for(int i=start;i<end;i++){
total += Math.abs(heights[i] - heights[i+1]);
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download