상세 컨텐츠

본문 제목

[LeetCode][Python]2870. Minimum Number of Operations to Make Array Empty

공부

by 근성 2024. 1. 4. 10:38

본문

https://leetcode.com/problems/minimum-number-of-operations-to-make-array-empty/description/?envType=daily-question&envId=2024-01-04

 

Minimum Number of Operations to Make Array Empty - LeetCode

Can you solve this real interview question? Minimum Number of Operations to Make Array Empty - You are given a 0-indexed array nums consisting of positive integers. There are two types of operations that you can apply on the array any number of times: * Ch

leetcode.com


이 문제는 숫자로 이루어진 list가 주어질때,

3개의 같은것, 2개의 같은것 끼리 지울 수가 있다.

 

이런 배열이라면

[2,3,3,2,2,4,2,3,4]

[3, 3, 2, 4, 2, 3, 4]

[3, 3, 4, 3, 4]

[4, 4]

[]

이런식으로 지운다는 말이다.

 

배열의 원소를 모두 지울 수 있는 최소한의 지움 횟수를 구하는것이 문제이다.

지우지 못하는 경우라면 -1을 반환하면 된다.

 

지우지 못하는 경우가 어떤경우일까?

주어진 배열에서 1개만 가지고 있는 경우이다.

예를 들면 이런 경우이다.

[2,1,2,2,3,3]

1이 1개만 있으니 지울 수 있는 조건이 없다.

 

이 문제는 Counter를 통한 접근이 쉬워보였다.

반복문을 통해서 Counter.values()에 접근했을 때,

1의 값을 가지면 -1을 반환하고,

1이 아닌 다른 값이라면 제일 크게 지울 수 있는 3이라는 값을 나눠주어 올려주는 ceil(c/3)을 사용한다.

class Solution:
    def minOperations(self, nums: List[int]) -> int:
        answer = 0
        counter = Counter(nums)
        for c in counter.values():
            if c == 1:
                return -1
            answer += ceil(c / 3)
        return answer

 

관련글 더보기

댓글 영역