Remove both the minimum and maximum elements from an array using the fewest deletions from either end.
Remove Minimum and Maximum From Array
gfgGiven an array of distinct integers, you may delete elements only from the front or the back of the array. Your goal is to remove both the minimum element and the maximum element with the minimum total number of deletions.
Return that minimum number of deletions.
A deletion removes exactly one element from either end of the current array. You do not need to preserve the order of the remaining elements beyond the fact that removals happen from the ends.
Input Format
- A single array of distinct integers.
- The array length is at least 1.
- Values are integers.
Output Format
- Return one integer: the minimum number of end deletions needed to remove both the smallest and largest values.
Constraints
- The array contains distinct values.
- You may delete only from the front or the back.
- Every deletion removes exactly one element.
- Return the minimum number of deletions required to remove both the minimum and maximum elements.
Example 1
Input
[2,10,7,5,4,1,8,6]
Output
5
Explanation
The minimum is 1 and the maximum is 10. One optimal strategy is to delete 2 elements from the front and 3 from the back, removing [2,10,7,5,4] and leaving [1,8,6] out of scope. The minimum deletions needed overall is 5.
Example 2
Input
[0,-4,19,1,8,-2,-3,5]
Output
3
Explanation
The minimum is -4 and the maximum is 19. Removing 2 elements from the front and 1 from the back is optimal, for a total of 3 deletions.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.