Where the climb turns into a descent
A pressure trace rises to a single peak and then falls away. The analysis wants the position of the peak, and the traces are long.
- The readings rise strictly to one peak, then fall strictly away.
- There is exactly one peak; it may be the first or the last reading.
- Return its position, counting from zero.
- An empty trace has no peak: return -1.
peak_position(trace: list<int>) → int
Where you start
def peak_position(trace: list[int]) -> int:
Worked examples
| Call | Result |
|---|---|
peak_position([1, 3, 5, 4, 2]) | 2 |
peak_position([1, 2, 3]) | 2 |
peak_position([9, 5, 1]) | 0 |
peak_position([7]) | 0 |
Hint
Compare a reading with the one after it. Still climbing means the peak is further right; already falling means it is here or to the left.
Reference solution in Python
def peak_position(trace: list[int]) -> int:
if not trace:
return -1
lo, hi = 0, len(trace) - 1
while lo < hi:
mid = (lo + hi) // 2
if trace[mid] < trace[mid + 1]:
lo = mid + 1
else:
hi = mid
return lo