LeetCode 2091: Removing Minimum and Maximum From Array Solution
Master LeetCode problem 2091 (Removing Minimum and Maximum From Array), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation:
To solve this problem, we can first find the indices of the minimum and maximum elements in the given array. Then, we can calculate the minimum number of deletions required to remove these elements. We can do this by considering the number of elements that need to be removed from the front and back of the array.
Here is the algorithm:
- Find the indices of the minimum and maximum elements in the array.
- Calculate the minimum number of deletions required by considering removing elements from the front and back of the array.
- Return the minimum number of deletions.
Time complexity: O(n) where n is the number of elements in the array. Space complexity: O(1)
Solution Code
class Solution {
public int minDeletions(int[] nums) {
int minIndex = 0, maxIndex = 0;
for (int i = 1; i < nums.length; i++) {
if (nums[i] < nums[minIndex]) {
minIndex = i;
}
if (nums[i] > nums[maxIndex]) {
maxIndex = i;
}
}
int minDeletionsFront = Math.min(minIndex, nums.length - maxIndex - 1);
int minDeletionsBack = Math.min(maxIndex, nums.length - minIndex - 1);
return minDeletionsFront + minDeletionsBack;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2091 (Removing Minimum and Maximum From Array)?
This page provides optimized solutions for LeetCode problem 2091 (Removing Minimum and Maximum From Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2091 (Removing Minimum and Maximum From Array)?
The time complexity for LeetCode 2091 (Removing Minimum and Maximum From Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2091 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2091 in Java, C++, or Python.