Drill

ProblemsC# › patterns

Where the climb turns into a descent

mediumpatternsBinary searchArraysC#

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.

PeakPosition(trace: list<int>) → int

C# 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.

Solve it in Python →

Where you start

public int PeakPosition(List<int> trace) {
    
}

Worked examples

CallResult
PeakPosition(new List<int> { 1, 3, 5, 4, 2 })2
PeakPosition(new List<int> { 1, 2, 3 })2
PeakPosition(new List<int> { 9, 5, 1 })0
PeakPosition(new List<int> { 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 C#
public int PeakPosition(List<int> trace) {
    if (trace.Count == 0) return -1;
    int lo = 0, hi = trace.Count - 1;
    while (lo < hi) {
        int mid = (lo + hi) / 2;
        if (trace[mid] < trace[mid + 1]) lo = mid + 1;
        else hi = mid;
    }
    return lo;
}

The same problem in another language

More patterns problems in C#