| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.TakeGiftsFromTheRichestPile; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class TakeGiftsFromTheRichestPilePriorityQueue : ITakeGiftsFromTheRichestPile |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O((n + k) * log n) |
| | 19 | | /// Space complexity - O(n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="gifts"></param> |
| | 22 | | /// <param name="k"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public long PickGifts(int[] gifts, int k) |
| 2 | 25 | | { |
| 2 | 26 | | var giftsPriorityQueue = new PriorityQueue<int, int>(); |
| | 27 | |
|
| 24 | 28 | | foreach (var gift in gifts) |
| 9 | 29 | | { |
| 9 | 30 | | giftsPriorityQueue.Enqueue(gift, -gift); |
| 9 | 31 | | } |
| | 32 | |
|
| 20 | 33 | | for (var i = 0; i < k; i++) |
| 8 | 34 | | { |
| 8 | 35 | | var gift = giftsPriorityQueue.Dequeue(); |
| | 36 | |
|
| 8 | 37 | | gift = (int)Math.Sqrt(gift); |
| | 38 | |
|
| 8 | 39 | | giftsPriorityQueue.Enqueue(gift, -gift); |
| 8 | 40 | | } |
| | 41 | |
|
| 2 | 42 | | long remainingGifts = 0; |
| | 43 | |
|
| 11 | 44 | | while (giftsPriorityQueue.Count > 0) |
| 9 | 45 | | { |
| 9 | 46 | | var gift = giftsPriorityQueue.Dequeue(); |
| | 47 | |
|
| 9 | 48 | | remainingGifts += gift; |
| 9 | 49 | | } |
| | 50 | |
|
| 2 | 51 | | return remainingGifts; |
| 2 | 52 | | } |
| | 53 | | } |