How to Build a Running Maximum List in Python
Compute a list where each element is the maximum of all numbers seen so far from an input list.
Python code
14 linesdef running_maximum(numbers):
result = []
current_max = float('-inf')
for num in numbers:
if num > current_max:
current_max = num
result.append(current_max)
return result
if __name__ == "__main__":
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
max_list = running_maximum(numbers)
print(f"Input: {numbers}")
print(f"Output: {max_list}")
Output
Input: [3, 1, 4, 1, 5, 9, 2, 6]
Output: [3, 3, 4, 4, 5, 9, 9, 9]
How it works
The function running_maximum iterates over each number once. It maintains a current_max variable that holds the largest value encountered so far. For each number, if it's greater than the current max, the max is updated; otherwise, it stays the same. The updated max is then appended to the result list. This algorithm runs in O(n) time and uses O(1) extra space besides the output list.
Common mistakes
- Forgetting to initialize `current_max` properly; using 0 can break for negative numbers.
- Updating `current_max` only when a new max is found but appending the wrong value.
- Trying to use `max()` on the entire prefix each time, leading to O(n²) complexity.
Variations
- Use `itertools.accumulate(numbers, max)` to achieve the same result in one line.
- Use a list comprehension with a temporary variable if you prefer a functional style.
Real-world use cases
- Tracking the highest score seen so far while processing a stream of game events.
- Calculating cumulative record highs in financial time series data for analytics dashboards.
- Monitoring peak resource usage (like CPU or memory) over a series of measurements.
Sponsored
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.