Problem Description
Given a 0-indexed array of distinct integers, remove both the minimum and maximum elements by only deleting elements from the front or the back of the array. The goal is to determine the minimum number of deletions needed to remove both these elements.
Key Insights
- First, determine the indices of the minimum and maximum elements.
- Since deletions can only occur from either end of the array, consider three strategies:
- Removing both elements by deleting from the front.
- Removing both elements by deleting from the back.
- Removing one element from the front and the other from the back.
- Choose the strategy that minimizes the total number of deletions.
Space and Time Complexity
Time Complexity: O(n) – We iterate through the array once to locate the minimum and maximum elements. Space Complexity: O(1) – Only a constant amount of extra space is used.
Solution
The solution involves:
- Iterating through the array to find the positions (indices) of the minimum and maximum elements.
- Considering three potential deletion strategies:
- Remove from the front until the farther of the two indices is removed.
- Remove from the back until the closer of the two indices (from the back) is removed.
- Remove one element from the front (up to the smaller index) and the other from the back (from the larger index).
- Computing the number of deletions for each strategy and returning the minimum value.
Data structures used include simple integer variables to store indices and counts. The approach is greedy because at each step, we choose the deletion direction that minimizes the overall count.