Arrays and Iteration
Find Maximum
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 with3. - The loop is
for i = 2, #arr do, so#arrsupplies the upper bound8for this dense table with nonilgaps. - Each pass reads
arr[i]and compares withif arr[i] > best then. - Only larger values assign
best = arr[i]; equal or smaller values leave the currentbestunchanged. - The replay uses language-neutral position labels: its
arr[0]seed is Lua'sarr[1], and its scan positionsi=1throughi=7correspond to Lua loop indexes2through8. - The replay starts with
best = 3, then keeps3for value1, replaces it with4, keeps4for value1, replaces it with5, then replaces it with9. - The final values
2and6do not replace9. print(best)writes the final maximum as9.
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.