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

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