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 Scala DSA version keeps the same data and final output as every other DSA book in this wave.

Basic Implementation

basic.scala
Replay: real traced execution (multi-file project)
object Main {
	def main(args: Array[String]): Unit = {
		val arr = Array(3, 1, 4, 1, 5, 9, 2, 6)
		var best = arr(0)
		for (i <- 1 until arr.length) {
			if (arr(i) > best) {
				best = arr(i)
			}
		}
		println(best)
	}
}
  1. arr ← [3, 1, 4, 1, 5, 9, 2, 6], best ← 3

    1object Main {2	def main(args: Array[String]): Unit = {
    values this step[3, 1, 4, 1, 5, 9, 2, 6]arr3best
  2. replaced ← no

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

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

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

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

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

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

    5for (i <- 1 until arr.length) {6	if (arr(i) > best) {7		best = arr(i)
    values this stepnoreplaced7i6arr[i]9best
  9. stdout ← 9

    9	}10	println(best)11}
    values this step9stdout9best

Complexity

  • Time: O(n)
  • Space: O(1)

Implementation notes

  • val arr = Array(3, 1, 4, 1, 5, 9, 2, 6) binds the Scala Array[Int] reference for this replay; the array contents are only read.
  • var best = arr(0) seeds the mutable running maximum from the first element, so the loop can start at the second slot.
  • The loop for (i <- 1 until arr.length) uses Scala's exclusive until range, scanning indices 1 through 7.
  • Array reads use parentheses, arr(i), and the comparison is direct Int ordering: only arr(i) > best replaces the current maximum.
  • The trace keeps best = 3 at index 1, updates to 4 at index 2, keeps 4 at index 3, updates to 5 at index 4, and updates to 9 at index 5.
  • Later values 2 and 6 do not replace best, so println(best) writes the exact output 9.