網頁

2024年10月14日 星期一

Python C++ heap priority queue速解L eetcode 2530 Maximal Score After Appl...


Python CPP heap priority queue速解L eetcode 2530. Maximal Score After Applying K Operations
heap/priority queue是重要的資料結構,無論是C++的std::priority_queue或是python的heapq都可以拿來練習這題用貪婪演算可解的問題
----------
Python解請進

Heap/priority queue is an important data structure. Whether it is C++'s std::priority_queue or Python's heapq, you can use it to practice this problem that can be solved using greedy algorithm.

[Python C++計數速解Leetcode 945 Minimum Increment to Make Array Unique]https://www.youtube.com/watch?v=tS-kunvQwcc
class Solution:
    def maxKelements(self, nums: List[int], k: int) -> int:
        heapify(pq:=[-x for x in nums])
        score=0
        for i in range(k):
            x=-heappop(pq)
            score+=x
            if x==1:
                score+=k-1-i
                break
            heappush(pq, -((x+2)//3))
        return score
        

沒有留言:

張貼留言

HTML 編輯器