Skip to content

Commit

Permalink
Solve LeetCode #506 'Relative Ranks' [Easy].
Browse files Browse the repository at this point in the history
  • Loading branch information
eminencegrs committed Dec 12, 2024
1 parent 9c411f4 commit d58f274
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
namespace LeetCode.Challenges.Problems05xx.N_0506_RelativeRanks;

public static class MaxHeapSolution
{
public static string[] FindRelativeRanks(int[] scores)
{
var priorityQueue = new PriorityQueue<(int Score, int Index), int>();
for (var i = 0; i < scores.Length; i++)
{
// The negative score is used for max-heap behavior.
priorityQueue.Enqueue((scores[i], i), -scores[i]);
}

var result = new string[scores.Length];
var rank = 1;
while (priorityQueue.Count > 0)
{
var (_, index) = priorityQueue.Dequeue();
result[index] = rank switch
{
1 => "Gold Medal",
2 => "Silver Medal",
3 => "Bronze Medal",
_ => rank.ToString()
};

rank++;
}

return result;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using FluentAssertions;
using LeetCode.Challenges.Problems05xx.N_0506_RelativeRanks;
using Xunit;

namespace LeetCode.Challenges.UnitTests.Problems05xx.N_0506_RelativeRanks;

public class MaxHeapSolutionTests
{
[Theory]
[ClassData(typeof(TestData))]
public void GivenScores_WhenFindRelativeRanks_ThenResultAsExpected(
int[] scores, string[] expectedResult)
{
MaxHeapSolution.FindRelativeRanks(scores).Should().BeEquivalentTo(expectedResult);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System.Collections;

namespace LeetCode.Challenges.UnitTests.Problems05xx.N_0506_RelativeRanks;

public class TestData : IEnumerable<object[]>
{
public IEnumerator<object[]> GetEnumerator()
{
yield return
[
new[] { 5, 4, 3, 2, 1 },
new[] { "Gold Medal", "Silver Medal", "Bronze Medal", "4", "5" }
];

yield return
[
new[] { 10, 3, 8, 9, 4 },
new[] { "Gold Medal", "5", "Bronze Medal", "Silver Medal", "4" }
];
}

IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator();
}

0 comments on commit d58f274

Please sign in to comment.