Problems › TypeScript › patterns
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.
peakPosition(trace: list<int>) → int
Where you start
function peakPosition(trace: number[]): number {
}
Worked examples
| Call | Result |
|---|---|
peakPosition([1,3,5,4,2]) | 2 |
peakPosition([1,2,3]) | 2 |
peakPosition([9,5,1]) | 0 |
peakPosition([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 TypeScript
function peakPosition(trace: number[]): number {
if (trace.length === 0) return -1;
let lo = 0;
let hi = trace.length - 1;
while (lo < hi) {
const mid = Math.floor((lo + hi) / 2);
if (trace[mid] < trace[mid + 1]) lo = mid + 1;
else hi = mid;
}
return lo;
}