Skip to main content
Back to problems
#2091
Medium Algorithms

Removing minimum and maximum from array

Array Greedy
56.2% acceptance
Feb 25, 2026
1040
57
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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn minimum_deletions(nums: Vec<i32>) -> i32 {
    let n = nums.len();
    if n == 1 {
      return 1;
    }
    let min_pos = nums.iter().enumerate().min_by_key(|&(_, &v)| v).unwrap().0;
    let max_pos = nums.iter().enumerate().max_by_key(|&(_, &v)| v).unwrap().0;

    let left = min_pos.min(max_pos);   // smaller index
    let right = min_pos.max(max_pos);  // larger index

    // Option 1: remove both from left -> right + 1 deletions
    let opt1 = (right + 1) as i32;
    // Option 2: remove both from right -> n - left deletions
    let opt2 = (n - left) as i32;
    // Option 3: remove left one from front, right one from back -> (left+1) + (n-right) deletions
    let opt3 = (left + 1 + n - right) as i32;

    opt1.min(opt2).min(opt3)
  }
}