algo/leetcode
2091. Removing Minimum and Maximum From Array
sourmc
2024. 10. 14. 00:47
https://leetcode.com/problems/removing-minimum-and-maximum-from-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.
class Solution:
def minimumDeletions(self, nums: List[int]) -> int:
result = sys.maxsize
minIdx = nums.index(min(nums))
maxIdx = nums.index(max(nums))
# 1. each other are different
result = min(min(minIdx + 1, maxIdx + 1) + min(len(nums) - minIdx, len(nums) - maxIdx), result)
# 2. both are front
result = min(max(minIdx + 1, maxIdx + 1), result)
# 3. both are back
result = min(max(len(nums) - minIdx, len(nums) - maxIdx), result)
return result
There are 3 ways of removing element. Let's call the maximum element's index 'M' and the minimum's 'm'
- Both elements are removed from the front of the array. ->
max(M + 1, m + 1)
- Both elements are removed from the back of the array. ->
max(len(str) - M, len(str) - m)
- One element is removed from the back of the array and the another is front ->
min(M + 1, m + 1) + min(len(str) - M, len(str) - m)
Now we just get a minimum value of these number of cases.