Scan the array once, keeping the largest value seen so far. The replay highlights when a candidate replaces the running maximum.

Algorithm

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.

Basic Implementation

basic.R
Replay: real traced execution (multi-file project)
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 = "")
  1. arr ← [3, 1, 4, 1, 5, 9, 2, 6], best ← 3

    1arr <- c(3, 1, 4, 1, 5, 9, 2, 6)2best <- arr[1]
    values this step[3, 1, 4, 1, 5, 9, 2, 6]arr3best
  2. replaced ← no

    4while (i <= length(arr)) {5  if (arr[i] > best) {6    best <- arr[i]
    values this stepnoreplaced1i1arr[i]3best
  3. best ← 4, replaced ← yes

    4while (i <= length(arr)) {5  if (arr[i] > best) {6    best <- arr[i]
    values this step3 4bestyesreplaced2i4arr[i]
  4. replaced ← no

    4while (i <= length(arr)) {5  if (arr[i] > best) {6    best <- arr[i]
    values this stepnoreplaced3i1arr[i]4best
  5. best ← 5, replaced ← yes

    4while (i <= length(arr)) {5  if (arr[i] > best) {6    best <- arr[i]
    values this step4 5bestyesreplaced4i5arr[i]
  6. best ← 9, replaced ← yes

    4while (i <= length(arr)) {5  if (arr[i] > best) {6    best <- arr[i]
    values this step5 9bestyesreplaced5i9arr[i]
  7. replaced ← no

    4while (i <= length(arr)) {5  if (arr[i] > best) {6    best <- arr[i]
    values this stepnoreplaced6i2arr[i]9best
  8. replaced ← no

    4while (i <= length(arr)) {5  if (arr[i] > best) {6    best <- arr[i]
    values this stepnoreplaced7i6arr[i]9best
  9. stdout ← 9

    1arr <- c(3, 1, 4, 1, 5, 9, 2, 6)2best <- arr[1]
    values this step9stdout9best

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 with 3.
  • i <- 2 starts the scan at the second R slot, because slot 1 is already stored in best.
  • The loop guard is while (i <= length(arr)), so the last checked R index is 8.
  • Each candidate is read as arr[i]; the comparison arr[i] > best is a scalar numeric comparison for this data.
  • When a larger value appears, best <- arr[i] rebinds the scalar best.
  • The checked replay keeps best at 3 for value 1, updates to 4, stays 4 for the next 1, updates to 5, then updates to 9.
  • The final two values, 2 and 6, do not replace 9.

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 is 9.