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