Write a function that takes a slice of integers and returns the largest one.
maxValue(nums)
You may assume the slice contains at least one number.
maxValue([4, 7, 2, 8, 10, 9]) // → 10
maxValue([-5, -1, -44, -3]) // → -1
maxValue([42,]) // → 42
You want the single biggest number in a list. No need to sort anything or compare every pair — just walk through once and remember the biggest one you've seen so far.
It's tempting to write max = 0 and compare everything against it. That works for [4, 7, 2, 8, 10, 9], but it breaks for [-5, -1, -44, -3] — every number there is negative, so none of them ever beats 0, and you'd wrongly return 0 even though it never appeared in the list.
The fix: seed your running max with the first element of the list, not a made-up number. That way the answer is always something that actually showed up in the input.
You touch each number exactly once and only ever hold one number in memory — the running max. That's O(n) time and O(1) space: the work grows with the list, but the memory never does.
"Seed with the first element, then compare-and-replace" shows up everywhere in DSA — finding a minimum, the longest/shortest of something, a running total. Any time a problem asks for "the biggest/smallest X in a collection," try this first.
import unittest
class TestMaxValue(unittest.TestCase):
def test_typical_case(self):
self.assertEqual(max_value([4, 7, 2, 8, 10, 9]), 10)
def test_all_negative(self):
self.assertEqual(max_value([-5, -1, -44, -3]), -1)
def test_single_element(self):
self.assertEqual(max_value([42]), 42)
def max_value(nums):
m = nums[0]
for v in nums[1:]:
if v > m:
m = v
return m
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.