Ctrl K

Cheapest Peak Triple

Medium
The array heights lists the heights of points along a trail. A triple of indices i < j < k is a peak if point j is strictly higher than the other two: heights[i] < heights[j] and heights[k] < heights[j]. The indices do not have to be adjacent. Return the smallest possible sum heights[i] + heights[j] + heights[k] over all peaks. If there is no peak, return -1.
Example 1
heights=[7, 2, 9, 4, 6, 3] → 9

The triple 2, 4, 3 (indices 1, 3, 5): the peak 4 is above both sides, and the sum is 9. Nothing cheaper exists.

Example 2
heights=[1, 2, 3, 4] → -1

Heights only grow, so no peak has a lower value to its right. The answer is -1.

Example 3
heights=[5, 5, 5, 6, 5] → 16

The only possible peak is 6, with 5 on each side, for a sum of 16.

Constraints
  • 3 ≤ len(heights) ≤ 10⁵
  • 1 ≤ heights[i] ≤ 10⁸
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTwo Boards Holding Water MediumZero-Sum Triples MediumTriple Sum Nearest the Target MediumFour Numbers to a Target MediumNext Arrangement in Order Medium
loading Python…
Input
heights=[7, 2, 9, 4, 6, 3]
Expected
9

Run checks the first 3 tests in your browser. Submit checks all 107 tests on the server, hidden ones included.