herrDeng網內搜尋

自訂搜尋

Ads

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
  1. class Solution:
  2. def maxKelements(self, nums: List[int], k: int) -> int:
  3. heapify(pq:=[-x for x in nums])
  4. score=0
  5. for i in range(k):
  6. x=-heappop(pq)
  7. score+=x
  8. if x==1:
  9. score+=k-1-i
  10. break
  11. heappush(pq, -((x+2)//3))
  12. return score

沒有留言:

Related Posts Plugin for WordPress, Blogger...

熱門文章