By LearnAllStudents Editorial Team. Source check dates are listed below.
Follow the worked example
For [−4, −7, −1, −1], initialise best = 0. At index 1, −7 does not beat −4.
At index 2, −1 beats −4, so set best = 2. At index 3, −1 ties; only replacing on a strictly larger value keeps index 2.
Return best to give the position, or values[best] if the prompt requests the value.
Place the listing inside a Java class. Try the worked example’s inputs from its main method.
static int firstMaximumIndex(int[] values) {
if (values.length == 0) {
return -1;
}
int best = 0;
for (int i = 1; i < values.length; i++) {
if (values[i] > values[best]) {
best = i;
}
}
return best;
}Write the invariant for the loop
After processing each prefix of the array, the saved index should point to the best value in that prefix. If earlier ties must win, update only on a strictly greater value. Starting from the first element makes the invariant valid for all-negative data too.
Try it yourself
For [6, 1, 6, 3], what index is returned when the earliest maximum wins?
Check your reasoning
Index 0. The later 6 ties but does not replace the earliest one.
Use the idea in a different situation
What changes when you replace > with >=?
Check the second task
The later tied maximum is accepted, so index 2 wins.
For parents
Ask, “Which index should stay saved if the next value ties the current maximum?”
They should refer to the tie rule and keep the first index when the update uses strict greater-than.
Trace one row per visited index with columns for value, previous best and new best.
How a tutor would approach this
Write down the expected output or state before running the Java code. Compare it with the actual output, trace where they first differ and test the fix against another input that arrives at the same kind of boundary.
Frequently asked questions
What mistake should I look for first?
Initialising a maximum value to zero fails when all values are negative.
How can I use this with a longer practice set?
Read the current course framework and official sample questions before deciding how to practise this technique in an exam-length task.
Are these official past-paper questions?
The worked example and practice tasks here are original. The sources section links to the official material for your course.
How can I tell if I can use the method on a new question?
Try the second task with the worked example covered. Explain which step needs to change and why before checking the answer.
Official sources
- College Board AP Computer Science A course and exam description (checked 2026-11-26)
Related pages
Try a free 30-minute demo
Work through a question with a tutor. No payment needed.
Request a free 30-minute demo