-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Solve LeetCode #2558 using a priority queue.
- Loading branch information
1 parent
92cd292
commit 9c411f4
Showing
2 changed files
with
44 additions
and
0 deletions.
There are no files selected for viewing
29 changes: 29 additions & 0 deletions
29
...rc/LeetCode.Challenges/Problems25xx/N_2558_TakeGiftsFromTheRichestPile/MaxHeapSolution.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |
15 changes: 15 additions & 0 deletions
15
...llenges.UnitTests/Problems25xx/N_2558_TakeGiftsFromTheRichestPile/MaxHeapSolutionTests.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} |