2091. Removing Minimum and Maximum From Array
MediumView on LeetCode
Time: O(n)
Space: O(1)
Advertisement
Approach
Find min and max indices; try 3 removal strategies (both from left, both from right, one each side).
Key Techniques
Array
Array problems involve manipulating elements stored in a contiguous block of memory. Key techniques include two-pointer traversal, prefix sums, sliding windows, and in-place partitioning. In C#, arrays are zero-indexed and fixed in size — use List<T> when you need dynamic resizing.
Greedy
Greedy algorithms make locally optimal choices at each step, hoping to reach a global optimum. Greedy works when a problem has the "greedy choice property" and "optimal substructure". Common applications: interval scheduling, activity selection, Huffman coding, and jump game.
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));
}
}Advertisement
Was this solution helpful?