파비의 매일매일 공부기록

2023.04.25 Today's Challenge 본문

Problem Solving/LeetCode

2023.04.25 Today's Challenge

fabichoi 2023. 4. 25. 23:45

https://leetcode.com/problems/last-stone-weight/

 

Last Stone Weight - LeetCode

Can you solve this real interview question? Last Stone Weight - You are given an array of integers stones where stones[i] is the weight of the ith stone. We are playing a game with the stones. On each turn, we choose the heaviest two stones and smash them

leetcode.com

최대 힙으로 푸는 문제!

class Solution:
    def lastStoneWeight(self, stones: List[int]) -> int:
        mh = [-stone for stone in stones]
        heapq.heapify(mh)

        while len(mh) > 1:
            stone1 = heapq.heappop(mh)
            stone2 = heapq.heappop(mh)

            if stone1 != stone2:
                heapq.heappush(mh, stone1 - stone2)
        
        if mh:
            return -mh[0]

        return 0
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

2023.04.27 Today's Challenge  (0) 2023.04.27
2023.04.26 Today's Challenge  (0) 2023.04.26
2023.04.24 Today's Challenge  (0) 2023.04.24
2023.04.23 Today's Challenge  (1) 2023.04.23
2023.04.22 Today's Challenge  (0) 2023.04.22
Comments