AP® Computer Science A · Unit 4 · Topic 4.5

Finding the Maximum and Its Index

Finding the maximum means walking the array once, keeping a running best value (or its index) and swapping it in whenever a bigger element shows up.

Finding the biggest value takes one pass because you only need to remember one thing: the best value seen so far. Start by assuming the first element is the maximum, then walk forward comparing each new element to your current best. Any time the new element is bigger, it replaces the running maximum. By the time you reach the end, whatever you're holding is guaranteed to be the largest value in the array, because every other element lost a comparison at some point. Finding the second biggest is harder because losing once doesn't disqualify a value from being second place overall — you'd need to track two candidates and handle the bookkeeping when the true max changes mid-pass.

Often you don't just want the maximum value, you want to know where it lives. The fix is simple: instead of storing the value itself, store its index. Initialize maxIndex to 0, and compare array[maxIndex] against array[i] as you loop. When array[i] is bigger, update maxIndex to i. At the end, array[maxIndex] gives you the value and maxIndex gives you the position — tracking the index gets you both for free, since you can always look the value up.

This pattern is the backbone of linear search, selection sort, and later recursive traversals in this unit — any algorithm that needs to find an extreme value or its location reuses this same one-pass comparison loop. Minimum works identically, just flip the comparison from greater-than to less-than.

Key terms

running maximum
The largest value found so far while scanning through the array, updated as you go.
index tracking
Storing the position of the best value found instead of the value itself, so you can recover both.
linear scan
Checking every element exactly once, in order, without skipping or revisiting any.
tie-breaking
Using strictly-greater-than comparisons means the first occurrence of a repeated maximum is the one kept.

Watch it explained

  1. How it worksHow does tracking an index instead of a value tell you where the maximum sits?
  2. Worked exampleTrace the maximum and its index through {12, 45, 7, 45, 30} and settle the tie.
  3. Common mistakeWhy doesn't starting the maximum at the first element fail the way starting at zero does?
  4. Worked exampleFind the minimum of {8, -3, 14, -3, 0} and the first index where it turns up.

Check yourself

Your turn1 of 2
In an array, the running maximum is currently 42. The next element is 39. What is the running maximum after comparing it to this next element?

End of topic.