Find the Maximum Value in a Large Numerical Stream
Arrays & HashingAuto-graded · 18 test casesLast updated
Find the maximum integer in a sequence while accounting for empty inputs and signed values.
Given a list of signed 64-bit integers a, return the maximum value contained in the list.
If the list is empty, return None.
Constraints
- $0 \le \text{len}(a) \le 10^5$
- Each element in
afits within a standard signed 64-bit integer ($-2^{63} \le a[i] \le 2^{63} - 1$).
Examples
Example 1
Input: find_maximum_value([3, 1, 9, -4, 9])
Output: 9
Example 2
Input: find_maximum_value([-9223372036854776000, -1, 0, 9223372036854776000])
Output: 9223372036854776000
Example 3
Input: find_maximum_value([])
Output: None
Hints
Hint 1
Be careful not to initialize your running maximum to 0, as all numbers in the input might be negative.
Hint 2
Consider how to handle the edge case where the input list contains no elements.
Hint 3
Iterate through the array line-by-line or item-by-item, updating a single candidate variable.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Finding the maximum of a sequence requires keeping track of the largest element seen so far as we traverse the input from left to right.
- Empty Check: If the list
ais empty, there is no maximum value, so we immediately returnNone. - Initialization: We initialize our tracking variable
current_maxwith the first elementa[0]. Initializing to0orINT_MINcan introduce subtle bugs (e.g., if the file contains only negative numbers or extreme 64-bit bounds). Initializing directly from the first element guarantees correct behavior regardless of value range. - Linear Scan: We iterate through the remaining elements. Whenever an element exceeds
current_max, we updatecurrent_max.
Complexity
- Time Complexity: $\mathcal{O}(N)$, where $N$ is the number of elements in
a. We inspect each item exactly once. - Space Complexity: $\mathcal{O}(1)$ auxiliary space, since we only store a single variable to maintain the running maximum.
from typing import List, Optional
def find_maximum_value(a: List[int]) -> Optional[int]:
if not a:
return None
current_max = a[0]
for num in a[1:]:
if num > current_max:
current_max = num
return current_max