The Trail problem from the 2010 AP Computer Science Exam is typical of free response problems that test arrays. The problem requires you to find the minimum and maximum in an array and access 2 elements of an array for each loop run.

Review the Trail free response problem with AP CS Tutor Brandon Horn.

## Trail Part (a): isLevelTrailSegment

```public boolean isLevelTrailSegment(int start, int end)
{
int minElevation = markers[start];
int maxElevation = markers[start];

for (int i = start + 1; i <= end; i++)
{
if (markers[i] < minElevation)
minElevation = markers[i];

if (markers[i] > maxElevation)
maxElevation = markers[i];
}

return maxElevation - minElevation <= 10;
}
```

## Trail Part (b): isDifficult

```public boolean isDifficult()
{
int significantChanges = 0;

for (int i = 1; i < markers.length; i++)
if (Math.abs(markers[i - 1] - markers[i]) >= 30)
significantChanges++;

return significantChanges >= 3;
}
```

## 4 thoughts on “Trail free response answer”

1. isnt the int maxElevation = markers[start]; be [end] ?

• Brandon Horn

No. Both the minimum and maximum values can be anything in the array. The first value could be the minimum, the maximum or both.

Since the loop starts at start+1, starting the maximum at the last value would fail if the first value was the maximum. If the loop started at start, it would not matter.

2. Pushkin Abbott

Hi . Why did you start the for loop from (start + 1) ?

• Brandon Horn

`minElevation` and `maxElevation` have already been set to `markers[start]`. Running the loop for `i == start` would just compare `markers[start]` to itself.