Skip to content

2091. Removing Minimum and Maximum From Array 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
 public:
  int minimumDeletions(vector<int>& nums) {
    const int n = nums.size();
    int a = ranges::min_element(nums) - nums.begin();
    int b = ranges::max_element(nums) - nums.begin();
    if (a > b)
      swap(a, b);
    return min({a + 1 + n - b, b + 1, n - a});
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
  public int minimumDeletions(int[] nums) {
    final int n = nums.length;

    int mn = Integer.MAX_VALUE;
    int mx = Integer.MIN_VALUE;
    int minIndex = -1;
    int maxIndex = -1;

    for (int i = 0; i < n; ++i) {
      if (nums[i] < mn) {
        mn = nums[i];
        minIndex = i;
      }
      if (nums[i] > mx) {
        mx = nums[i];
        maxIndex = i;
      }
    }

    final int a = Math.min(minIndex, maxIndex);
    final int b = Math.max(minIndex, maxIndex);

    // min(delete from front and back,
    //     delete from front,
    //     delete from back)
    return Math.min(a + 1 + n - b, Math.min(b + 1, n - a));
  }
}
1
2
3
4
5
6
7
8
class Solution:
  def minimumDeletions(self, nums: list[int]) -> int:
    n = len(nums)
    a = nums.index(min(nums))
    b = nums.index(max(nums))
    if a > b:
      a, b = b, a
    return min(a + 1 + n - b, b + 1, n - a)