Max value

Max value

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.

Examples

maxValue([4, 7, 2, 8, 10, 9])  // → 10
maxValue([-5, -1, -44, -3])    // → -1
maxValue([42,])                 // → 42

Thinking it through

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.

Why not start the running max at 0?

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.

Building the approach

  1. Take the first element as your best guess.
  2. Walk through the rest of the list, one number at a time.
  3. Whenever you see something bigger than your best, replace it.
  4. When you've seen everything, your best is the answer — nothing left could beat it.

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.

Why this generalizes

"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.

Tests

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)
main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.