deepakl.2000 - 1 year ago 51

Java Question

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

`start`

`end`

`start`

`end`

`{5, 3, 6, 7, 2}`

`start=2`

`end=4`

`1 + 5 = 6`

`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;

}

return total;

}

Answer Source

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]);
}
```