Removing Minimum and Maximum From Array - Problem

You are given a 0-indexed array of distinct integers nums.

There is an element in nums that has the lowest value and an element that has the highest value. We call them the minimum and maximum respectively. Your goal is to remove both these elements from the array.

A deletion is defined as either removing an element from the front of the array or removing an element from the back of the array.

Return the minimum number of deletions it would take to remove both the minimum and maximum element from the array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,10,7,5,4,1,8,6]
Output: 5
💡 Note: Min element is 1 at index 5, max element is 10 at index 1. The optimal strategy is to remove both from the front, requiring max(1,5) + 1 = 6 deletions. Actually, mixed strategy gives min(2,6) + min(6,2) = 2 + 2 = 4, and removing both from back gives 8 - min(1,5) = 7. So minimum is min(6,7,4) = 4. Wait, let me recalculate: from front = 6, from back = 7, mixed = 4. But the expected output is 5, let me verify the problem again.
Example 2 — Elements at Ends
$ Input: nums = [0,2,1,4,9,3]
Output: 3
💡 Note: Min element is 0 at index 0, max element is 9 at index 4. Strategy 1 (both from front): max(0,4) + 1 = 5. Strategy 2 (both from back): 6 - min(0,4) = 6. Strategy 3 (mixed): min(1,6) + min(5,2) = 1 + 2 = 3. Minimum is 3.
Example 3 — Small Array
$ Input: nums = [3,1]
Output: 2
💡 Note: Only 2 elements, so we must remove both. Min is 1 at index 1, max is 3 at index 0. Any strategy removes all elements: 2 deletions.

Constraints

  • 3 ≤ nums.length ≤ 105
  • -105 ≤ nums[i] ≤ 105
  • nums contains distinct values

Visualization

Tap to expand
Removing Minimum and Maximum From Array INPUT nums = [2,10,7,5,4,1,8,6] 2 i=0 10 i=1 MAX 7 i=2 5 i=3 4 i=4 1 i=5 MIN 8 i=6 6 i=7 Maximum (10 at i=1) Minimum (1 at i=5) Array length: n = 8 minIdx = 5, maxIdx = 1 left = 1, right = 5 ALGORITHM STEPS 1 Find min and max indices left=1 (max), right=5 (min) 2 Calculate 3 strategies Compare deletion options A: Both from front right + 1 = 5 + 1 = 6 B: Both from back n - left = 8 - 1 = 7 C: One from each side [BEST] (left+1) + (n-right) = 2 + 3 = 5 3 Return minimum min(6, 7, 5) = 5 FINAL RESULT Optimal Strategy C: Front deletions (2): 2 10 X X Back deletions (3): 1 8 6 X X X Output 5 Status: OK 2 + 3 = 5 deletions Key Insight: With greedy approach, we only have 3 possible strategies to consider: 1) Delete both from front 2) Delete both from back 3) One from each end The optimal solution is always min(right+1, n-left, left+1 + n-right) where left <= right. TutorialsPoint - Removing Minimum and Maximum From Array | Greedy - Optimal Strategy Selection
Asked in
Amazon 3 Microsoft 2
23.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen