๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ“š Study Note/LeetCode

2091. Removing Minimum and Maximum From Array

by Jellll_y 2023. 2. 1.

2091. Removing Minimum and Maximum From Array

Medium


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.

 

Example 1:

Input: nums = [2,10,7,5,4,1,8,6]
Output: 5
Explanation: 
The minimum element in the array is nums[5], which is 1.
The maximum element in the array is nums[1], which is 10.
We can remove both the minimum and maximum by removing 2 elements from the front and 3 elements from the back.
This results in 2 + 3 = 5 deletions, which is the minimum number possible.

 

Example 2:

Input: nums = [101]
Output: 1
Explanation:  
There is only one element in the array, which makes it both the minimum and maximum element.
We can remove it with 1 deletion.

 

 

์ฃผ์–ด์ง„ ๋ฐฐ์—ด์—์„œ ๊ฐ€์žฅ ํฐ ์ˆซ์ž์™€ ๊ฐ€์žฅ ์ž‘์€ ์ˆซ์ž๋ฅผ ์ œ๊ฑฐํ•  ๋•Œ

๋ช‡ ๋ฒˆ ๋งŒ์— ์ œ๊ฑฐํ•  ์ˆ˜ ์žˆ๋Š”์ง€ ์•Œ์•„๋‚ด๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

 

์ด๋•Œ ์ œ๊ฑฐํ•˜๋Š” ๋ฐฉ๋ฒ•์€ 3๊ฐ€์ง€์ž…๋‹ˆ๋‹ค.

case 1. ๋ฐฐ์—ด์˜ ์•ž์—์„œ๋ถ€ํ„ฐ ์ œ๊ฑฐํ•œ๋‹ค.

case 2. ๋ฐฐ์—ด์˜ ๋’ค์—์„œ๋ถ€ํ„ฐ ์ œ๊ฑฐํ•œ๋‹ค.

case 3. ๋ฐฐ์—ด์˜ ์•ž๊ณผ ๋’ค์—์„œ ๋ถ€ํ„ฐ ์ œ๊ฑฐํ•œ๋‹ค.

 

์˜์‚ฌ์ฝ”๋“œ

1. nums์˜ ๊ธธ์ด๊ฐ€ 1์ด๋ฉด 1์„ ๋ฆฌํ„ดํ•œ๋‹ค. 

2.  nums์—์„œ ๊ฐ€์žฅ ํฐ ์ˆ˜, ๊ฐ€์žฅ ์ž‘์€ ์ˆ˜์˜ ์ธ๋ฑ์Šค ๋ฒˆํ˜ธ๋ฅผ ์ฐพ๋Š”๋‹ค.

3. ๊ฐ case ๋ณ„๋กœ ์ œ๊ฑฐ ํšŸ์ˆ˜๋ฅผ ๊ตฌํ•˜๊ณ  ๊ทธ์ค‘ ๊ฐ€์žฅ ์ž‘์€ ํšŸ์ˆ˜์˜ ๊ฐ’์„ ๋ฆฌํ„ดํ•œ๋‹ค.

/**
 * @param {number[]} nums
 * @return {number}
 */
var minimumDeletions = function(nums) {
    if(nums.length===1) return 1
    
    const [minIdx, maxIdx] = findMinIdxAndMaxId(nums)
    
    const len = nums.length
    const left = Math.min(minIdx, maxIdx)
    const right = Math.max(minIdx, maxIdx)
    
    // case 1 : ์•ž์—์„œ ๋ถ€ํ„ฐ ์‚ญ์ œ right + 1
    // case 2 : ๋’ค์—์„œ ๋ถ€ํ„ฐ ์‚ญ์ œ len - left
    // case 3 : ์•ž ๋’ค์—์„œ ๋ถ€ํ„ฐ ์‚ญ์ œ  (left + 1) + (len - right)
    return Math.min(right + 1, len - left, left + 1 + len - right)
};

function findMinIdxAndMaxId(nums) {
    let minIdx = 0, maxIdx = 0 
    
    for(let i=0; i<nums.length;i++){
        if(nums[i] < nums[minIdx]) minIdx = i
        if(nums[i] > nums[maxIdx]) maxIdx = i
    }
    
    return [minIdx, maxIdx]
}

'๐Ÿ“š Study Note > LeetCode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

904. Fruit Into Baskets  (0) 2023.02.07
1091. Shortest Path in Binary Matrix  (0) 2023.02.06
209. Minimum Size Subarray Sum  (0) 2022.12.28
346. Moving Average from Data Stream  (0) 2022.12.26
2225. Find Players With Zero or One Losses  (0) 2022.11.28