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
Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
int peakPosition(List<Integer> trace) {
}
Worked examples
| Call | Result |
|---|---|
peakPosition(Main.<Integer>ls(1, 3, 5, 4, 2)) | 2 |
peakPosition(Main.<Integer>ls(1, 2, 3)) | 2 |
peakPosition(Main.<Integer>ls(9, 5, 1)) | 0 |
peakPosition(Main.<Integer>ls(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 Java
int peakPosition(List<Integer> trace) {
if (trace.isEmpty()) return -1;
int lo = 0, hi = trace.size() - 1;
while (lo < hi) {
int mid = (lo + hi) / 2;
if (trace.get(mid) < trace.get(mid + 1)) lo = mid + 1;
else hi = mid;
}
return lo;
}