Unit 2 Cycle 1 Day 16: Loop with Running Maximum
Share
Loop with Running Maximum
Section 2.10 — Loop Algorithms
Key Concept
Finding a running maximum (or minimum) requires initializing a variable before the loop and updating it inside the loop when a larger (or smaller) value is found. The standard pattern is: initialize max to the first element or Integer.MIN_VALUE, then loop through remaining elements comparing each to max. A common AP exam trap is initializing max to 0 — this fails when all values are negative. Always consider edge cases: empty input, all equal values, or the extreme value appearing first or last.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (C) 9
max starts at 3. i=1: 7>3, max=7. i=2: 2>7 false. i=3: 9>7, max=9. i=4: 4>9 false. Final max = 9.
Why Not the Others?
(A) 3 is only the initial value of max, which gets updated when larger values are found.
(B) 7 is the max after checking index 1, but 9 at index 3 is larger.
(D) 4 is the last element but not the largest.
Common Mistake
The running maximum pattern initializes max to the first element, then compares each remaining element. The loop starts at index 1 (not 0) to avoid comparing the first element to itself.
AP Exam Tip
The find-max algorithm always initializes max to the first element (not 0 or Integer.MIN_VALUE on the AP exam). Starting from index 1 is standard.