Member-only story

Leetcode 2091: Removing Minimum and Maximum From Array

Pierre-Marie Poitevin
3 min readNov 29, 2021

--

In this leetcode problem, we are asked to calculate the minimum amounts of “deletions” to remove the max and the min from an array.

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.

Here are some examples given:

Examples and contraints

We can see that to “delete” a number at index i, we must either delete all the items indexed 0to i, or delete all the items index i to n — 1.

Since we need to delete the min and the max elements of this array, we first traverse the array to find the min and max, and we remember their indices. This is done that way:

int min = 1000000;
int max = -1000000;
int minIndex = 0;
int maxIndex = 0;
int n = nums.length;
for (int i = 0 ; i < n; i++) {
int x = nums[i];
if (x < min) {
min = x;
minIndex = i;
}…

--

--

Pierre-Marie Poitevin
Pierre-Marie Poitevin

No responses yet