Arrays and strings · Exercise 5 of 100

Largest Array Element

In a nonempty array, use the first value as your largest value so far. Replace it whenever you see a larger value, which works even when every value is negative.

Try it yourself

A freezer records temperatures of [-9, -12, -3, -8, -5] degrees. What is the largest reading?

One-step hint

Place the freezer readings on a number line with zero at the right. Which reading lies farthest to the right?

Worked solution
  1. Start with -9. The reading -12 is lower, but -3 is higher, so keep -3.
  2. Both -8 and -5 are lower than -3, so the largest reading is -3.
DSA compiler

Explore the idea visually in the linear search lab.