DSA Factory
Free lessonsArrays · Stage 2 · Traversal with state · Step 1

Remember the best so far

Find the largest value in one pass. About 7 minutes.

You're looking through apartment listings for the biggest balcony. You don't write them all down: you just remember the biggest one you've seen so far, and swap it out whenever a bigger one turns up.

A loop can carry a value along in the same way. Keep one variable for "the biggest so far". At every box, compare: if this value is bigger, it becomes the new biggest. When the loop ends, it holds the answer.

Carry one value along: update it only when you beat it.
Keep the biggest so far
3
0
8
1
2
2
9
3
5
4
i

best starts at 3.

Move 1 of 5

Start with a real value, not 0

What should "the biggest so far" be before you've looked at anything? Starting at 0 feels natural, but try it on −5, −2, −9. No value beats 0, so you'd return 0, a number that isn't even in the list.

Start with the first box instead. It's always a real value, and until you've seen more, it really is the biggest.

Starting at 0: breaks when every number is negative.
Start with the first box: it's always a real value.
In code
best = nums[0]
for x in nums:
    if x > best:
        best = x
return best
Quick check

Someone starts "biggest so far" at 0, then keeps the bigger value at each box. What do they return for −5, −2, −9?

  1. A0
  2. B−2
  3. C−9
Show the answer

0. No value beats 0, so it never changes. That's why you start with the first box instead.

Your problem

Largest value

You get a list with at least one number. Return the largest number in it.

Example
nums = [3, 8, 2, 9, 5] → 9

1 ≤ n ≤ 1,000 · values can be negative

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding