2091. Removing Minimum and Maximum From Array
MediumView on LeetCode
Time: O(n)
Space: O(1)
Problem Overview
Removing Minimum and Maximum From Array (Medium) asks you to solve a structured algorithmic task. This is a common Array / Greedy pattern in coding interviews. Find min and max indices; try 3 removal strategies (both from left, both from right, one each side).
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
Find min and max indices; try 3 removal strategies (both from left, both from right, one each side).
2091.cs
C#
// Approach: Find min and max indices; try 3 removal strategies (both from left, both from right, one each side).
// Time: O(n) Space: O(1)
public class Solution
{
public int MinimumDeletions(int[] nums)
{
int n = nums.Length;
int mn = int.MaxValue;
int mx = int.MinValue;
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;
}
}
int a = Math.Min(minIndex, maxIndex);
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));
}
}Was this solution helpful?
Related Problems
- 11. Container With Most Water(Medium)
- 122. Best Time to Buy and Sell Stock II(Medium)
- 135. Candy(Hard)
- 179. Largest Number(Medium)
- 321. Create Maximum Number(Unknown)
- 330. Patching Array(Hard)