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.scala
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)
}
}
Complexity
- Time: O(n)
- Space: O(1)
Implementation notes
val arr = Array(3, 1, 4, 1, 5, 9, 2, 6)binds the ScalaArray[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 exclusiveuntilrange, scanning indices1through7. - Array reads use parentheses,
arr(i), and the comparison is directIntordering: onlyarr(i) > bestreplaces the current maximum. - The trace keeps
best = 3at index1, updates to4at index2, keeps4at index3, updates to5at index4, and updates to9at index5. - Later values
2and6do not replacebest, soprintln(best)writes the exact output9.
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.