Ctrl K

Trim Ends to Both Extremes

Medium
You are given an array values of distinct integers. In one move you may remove either the first or the last element of the array. You need to remove both the smallest and the largest element. Return the minimum number of moves that achieves this.
Example 1
values=[6, 3, 9, -2, 4, 1, 5] → 4

The maximum 9 is at position 2 and the minimum -2 at position 3. The cheapest is to take 4 elements from the front.

Example 2
values=[0, 8, 2, 4, 7, -1, 6] → 4

Take 2 from the front (reaching 8) and 2 from the back (reaching -1), 4 in total.

Example 3
values=[13] → 1

The only element is both the minimum and the maximum.

Constraints
  • 1 ≤ len(values) ≤ 10⁵
  • -10⁵ ≤ values[i] ≤ 10⁵
  • All numbers in values are distinct
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTwo Boards Holding Water MediumFewest Jumps to the End MediumReach the Last Cell MediumAs Many Trades as You Like MediumWhere to Start the Lap Medium
loading Python…
Input
values=[6, 3, 9, -2, 4, 1, 5]
Expected
4

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