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.
best starts at 3.
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.
best = nums[0]
for x in nums:
if x > best:
best = x
return bestSomeone starts "biggest so far" at 0, then keeps the bigger value at each box. What do they return for −5, −2, −9?
- A0
- B−2
- C−9
Show the answer
0. No value beats 0, so it never changes. That's why you start with the first box instead.
Largest value
You get a list with at least one number. Return the largest number in it.
nums = [3, 8, 2, 9, 5] → 9
1 ≤ n ≤ 1,000 · values can be negative