파비의 매일매일 공부기록

2023.02.24 Today's Challenge 본문

Problem Solving/LeetCode

2023.02.24 Today's Challenge

fabichoi 2023. 2. 24. 23:45

https://leetcode.com/problems/minimize-deviation-in-array/

 

Minimize Deviation in Array - LeetCode

Can you solve this real interview question? Minimize Deviation in Array - You are given an array nums of n positive integers. You can perform two types of operations on any element of the array any number of times: * If the element is even, divide it by 2.

leetcode.com

ㅠㅠ 어제 못해서 streak가 깨져버림 ㅠㅠ
Priority Queue를 활용해서 푸는 문제

class Solution:
    def minimumDeviation(self, nums: List[int]) -> int:
        if not nums:
            return float('inf')
        
        evens = []
        min_val = float('inf')

        for num in nums:
            if num % 2 == 0:
                heapq.heappush(evens, -num)
                min_val = min(num, min_val)
            else:
                heapq.heappush(evens, -num * 2)
                min_val = min(num * 2, min_val)
        
        res = float('inf')

        while evens[0] % 2 == 0:
            max_val = -heapq.heappop(evens)
            res = min(res, max_val - min_val)
            new_num = max_val // 2
            heapq.heappush(evens, -new_num)
            min_val = min(new_num, min_val)
        
        res = min(-evens[0] - min_val, res)
        return res
반응형

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

2023.02.26 Today's Challenge  (0) 2023.02.26
2023.02.25 Today's Challenge  (0) 2023.02.25
2023.02.23 Today's Challenge  (0) 2023.02.23
2023.02.22 Today's Challenge  (0) 2023.02.22
2023.02.21 Today's Challenge  (0) 2023.02.21
Comments