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

Basic Implementation

basic.lua
Replay: real traced execution (multi-file project)
arr = {3, 1, 4, 1, 5, 9, 2, 6}
best = arr[1]
for i = 2, #arr do
	if arr[i] > best then
		best = arr[i]
	end
end
print(best)
  1. arr ← [3, 1, 4, 1, 5, 9, 2, 6], best ← 3

    1arr = {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

    3for i = 2, #arr do4	if arr[i] > best then5		best = arr[i]
    values this stepnoreplaced1i1arr[i]3best
  3. best ← 4, replaced ← yes

    3for i = 2, #arr do4	if arr[i] > best then5		best = arr[i]
    values this step3 4bestyesreplaced2i4arr[i]
  4. replaced ← no

    3for i = 2, #arr do4	if arr[i] > best then5		best = arr[i]
    values this stepnoreplaced3i1arr[i]4best
  5. best ← 5, replaced ← yes

    3for i = 2, #arr do4	if arr[i] > best then5		best = arr[i]
    values this step4 5bestyesreplaced4i5arr[i]
  6. best ← 9, replaced ← yes

    3for i = 2, #arr do4	if arr[i] > best then5		best = arr[i]
    values this step5 9bestyesreplaced5i9arr[i]
  7. replaced ← no

    3for i = 2, #arr do4	if arr[i] > best then5		best = arr[i]
    values this stepnoreplaced6i2arr[i]9best
  8. replaced ← no

    3for i = 2, #arr do4	if arr[i] > best then5		best = arr[i]
    values this stepnoreplaced7i6arr[i]9best
  9. stdout ← 9

    7end8print(best)
    values this step9stdout9best

Complexity

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

Implementation notes

  • arr = {3, 1, 4, 1, 5, 9, 2, 6} is a Lua table used as an array.
  • Lua arrays are 1-based here: best = arr[1] seeds the scan with 3.
  • The loop is for i = 2, #arr do, so #arr supplies the upper bound 8 for this dense table with no nil gaps.
  • Each pass reads arr[i] and compares with if arr[i] > best then.
  • Only larger values assign best = arr[i]; equal or smaller values leave the current best unchanged.
  • The replay uses language-neutral position labels: its arr[0] seed is Lua's arr[1], and its scan positions i=1 through i=7 correspond to Lua loop indexes 2 through 8.
  • The replay starts with best = 3, then keeps 3 for value 1, replaces it with 4, keeps 4 for value 1, replaces it with 5, then replaces it with 9.
  • The final values 2 and 6 do not replace 9.
  • print(best) writes the final maximum as 9.