Unit 4 Cycle 1 Day 7: Finding Maximum

Unit 4 Foundation (Cycle 1) Day 7 of 28 Foundation

Finding Maximum

Section 4.3 — Common Array Algorithms

Key Concept

Finding the maximum value in an array requires a running maximum variable initialized to the first element (or Integer.MIN_VALUE) and a loop that compares each element. If an element is greater than the current maximum, update the maximum. A common AP exam trap is initializing the maximum to 0, which fails for arrays with all negative values. To find the index of the maximum, track both the max value and its index. The AP exam tests variations: minimum, first/last occurrence, and conditional maximum.

Consider the following code segment.

int[] data = {3, 7, 1, 9, 4}; int max = data[0]; for (int i = 1; i < data.length; i++) { if (data[i] > max) { max = data[i]; } } System.out.println(max);

What is printed?

Answer: (B) 9

max starts at data[0]=3. i=1: 7>3, max=7. i=2: 1>7 false. i=3: 9>7, max=9. i=4: 4>9 false. Final max=9.

Why Not the Others?

(A) 3 is the initial value but is replaced by larger values.

(C) 7 is max after index 1, but 9 at index 3 is larger.

(D) 4 is the last element but not the largest.

Common Mistake

Initialize max to the first element (not 0 or Integer.MIN_VALUE for the AP exam). Start the loop at index 1 since index 0 is already the initial max.

AP Exam Tip

Find-max pattern: (1) Initialize to first element. (2) Loop from index 1. (3) Update when current > max. This pattern appears on nearly every AP exam.

Review this topic: Section 4.3 — Common Array Algorithms • Unit 4 Study Guide
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.