Unit 4 Cycle 1 Day 7: Finding Maximum
Share
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.
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.