Running Maximum of a NumPy Array With np.maximum.accumulate
Quick Overview
Compute the running maximum of a 1-D NumPy array, where each output position holds the largest value seen so far, using np.maximum.accumulate with no Python loop. It tests ufunc methods, vectorized prefix operations, and edge cases such as empty input and NaN values.
Running Maximum of a NumPy Array With np.maximum.accumulate
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Given a 1-D NumPy array `a`, return its running maximum: output index `i` is the max of `a[0..i]` inclusive. Return a NumPy array of the same length.
```python
a = np.array([3, 1, 4, 1, 5, 9, 2, 6])
running_max(a)
# array([3, 3, 4, 4, 5, 9, 9, 9])
```
```hint Edge cases
`accumulate` keeps every intermediate value of the fold that `np.maximum.reduce` would compute. Check what your function returns for an empty array and whether the output dtype matches the input.
```
### Constraints & Assumptions
- Input is a 1-D array of numeric dtype.
- Empty input returns an empty array.
- Must use `np.maximum.accumulate`: no Python loop or list comprehension.
### What a Strong Answer Covers
- Calling `np.maximum.accumulate` and stating the recurrence it computes for each position.
- Time and space complexity of the single vectorized pass.
- Behavior on empty input and the dtype of the result.
- How NaN values move through `np.maximum`.
### Follow-up Questions
- How would you extend this to a running max along a chosen axis of a 2-D array?
- How do NaN values affect the result, and how could you handle them?
- How would you also return, for each position, the index of the element that holds the running maximum, still without a loop?
Overview: Compute the running maximum of a 1-D NumPy array, where each output position holds the largest value seen so far, using np.maximum.accumulate with no Python loop. It tests ufunc methods, vectorized prefix operations, and edge cases such as empty input and NaN values.