C++20 sections · 1024 units
Open in Course

Finding Maximum

Locating the largest element

Finding maximum mirrors the minimum algorithm. Start with max = arr[0], assuming first is largest. Loop through remaining elements, updating max when you find something larger. After the loop, max holds the biggest value.

The comparison uses greater-than instead of less-than. Write if (arr[i] > max) max = arr[i]; in your loop. Every element gets checked once. The algorithm runs in linear time. Sometimes you need the index of the maximum.

Track maxIndex alongside max. When updating max, also set maxIndex = i. This tells you where the maximum lives.