Skip to content

Commit

Permalink
Solve LeetCode #2558 using a priority queue.
Browse files Browse the repository at this point in the history
  • Loading branch information
eminencegrs committed Dec 12, 2024
1 parent 92cd292 commit 9c411f4
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
namespace LeetCode.Challenges.Problems25xx.N_2558_TakeGiftsFromTheRichestPile;

// Time Complexity: O(log n)
public static class MaxHeapSolution
{
public static long PickGifts(int[] gifts, int k)
{
PriorityQueue<int, int> maxHeap = new();
foreach (var gift in gifts)
{
maxHeap.Enqueue(gift, -gift);
}

for (var i = 0; i < k; i++)
{
var maxGift = maxHeap.Dequeue();
var remaining = (int)Math.Sqrt(maxGift);
maxHeap.Enqueue(remaining, -remaining);
}

var totalRemaining = 0L;
while (maxHeap.Count > 0)
{
totalRemaining += maxHeap.Dequeue();
}

return totalRemaining;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using LeetCode.Challenges.Problems25xx.N_2558_TakeGiftsFromTheRichestPile;
using Shouldly;
using Xunit;

namespace LeetCode.Challenges.UnitTests.Problems25xx.N_2558_TakeGiftsFromTheRichestPile;

public class MaxHeapSolutionTests
{
[Theory]
[ClassData(typeof(TestData))]
public void GivenGifts_WhenMinPickGifts_ThenResultAsExpected(int[] numbers, int k, long expectedResult)
{
MaxHeapSolution.PickGifts(numbers, k).ShouldBe(expectedResult);
}
}

0 comments on commit 9c411f4

Please sign in to comment.