Arrays and Iteration
Find Maximum
Scan the array once, keeping the largest value seen so far. The replay highlights when a candidate replaces the running maximum.
Algorithm
Basic Implementation
basic.R
arr <- c(3, 1, 4, 1, 5, 9, 2, 6)
best <- arr[1]
i <- 2
while (i <= length(arr)) {
if (arr[i] > best) {
best <- arr[i]
}
i <- i + 1
}
cat(best, "\n", sep = "")
Complexity
- Time: O(n)
- Space: O(1)
Implementation notes
arr <- c(3, 1, 4, 1, 5, 9, 2, 6)creates a numeric R vector with the pinned values.- R vectors are 1-based, so
best <- arr[1]seeds the running maximum with3. i <- 2starts the scan at the second R slot, because slot1is already stored inbest.- The loop guard is
while (i <= length(arr)), so the last checked R index is8. - Each candidate is read as
arr[i]; the comparisonarr[i] > bestis a scalar numeric comparison for this data. - When a larger value appears,
best <- arr[i]rebinds the scalarbest. - The checked replay keeps
bestat3for value1, updates to4, stays4for the next1, updates to5, then updates to9. - The final two values,
2and6, do not replace9.
Replay steps
seed from arr[1]: best = 3
arr[2] = 1: best stays 3
arr[3] = 4: best becomes 4
arr[4] = 1: best stays 4
arr[5] = 5: best becomes 5
arr[6] = 9: best becomes 9
arr[7] = 2: best stays 9
arr[8] = 6: best stays 9
cat(best, "\n", sep = "")prints only the final scalar and newline, so the output is9.
execution replay
The checked-in replay follows the language-neutral state table for `array-find-max`.
cross-language comparison
This R DSA version keeps the same data and final output as every other DSA book in this wave.