C# || How To Find The Minimum Rounds To Complete All Tasks Using C#
The following is a module with functions which demonstrates how to find the minimum rounds to complete all tasks using C#.
1. Minimum Rounds – Problem Statement
You are given a 0-indexed integer array tasks, where tasks[i] represents the difficulty level of a task. In each round, you can complete either 2 or 3 tasks of the same difficulty level.
Return the minimum rounds required to complete all the tasks, or -1 if it is not possible to complete all the tasks.
Example 1:
Input: tasks = [2,2,3,3,2,4,4,4,4,4]
Output: 4
Explanation: To complete all the tasks, a possible plan is:
- In the first round, you complete 3 tasks of difficulty level 2.
- In the second round, you complete 2 tasks of difficulty level 3.
- In the third round, you complete 3 tasks of difficulty level 4.
- In the fourth round, you complete 2 tasks of difficulty level 4.
It can be shown that all the tasks cannot be completed in fewer than 4 rounds, so the answer is 4.
Example 2:
Input: tasks = [2,3,3]
Output: -1
Explanation: There is only 1 task of difficulty level 2, but in each round, you can only complete either 2 or 3 tasks of the same difficulty level. Hence, you cannot complete all the tasks, and the answer is -1.
2. Minimum Rounds – Solution
The following is a solution which demonstrates how to find the minimum rounds to complete all tasks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
// ============================================================================ // Author: Kenneth Perkins // Date: Jul 1, 2023 // Taken From: http://programmingnotes.org/ // File: Solution.cs // Description: Demonstrates how to find minimum rounds to complete tasks // ============================================================================ public class Solution { public int MinimumRounds(int[] tasks) { var freq = new Dictionary<int, int>(); // Store the frequencies in the map. foreach (var task in tasks) { freq[task] = freq.GetValueOrDefault(task, 0) + 1; } int minimumRounds = 0; // Iterate over the task's frequencies. foreach (int count in freq.Values) { // If the frequency is 1, it's not possible to complete tasks. if (count == 1) { return - 1; } if (count % 3 == 0) { // Group all the task in triplets. minimumRounds += count / 3; } else { // If count % 3 = 1; (count / 3 - 1) groups of triplets and 2 pairs. // If count % 3 = 2; (count / 3) groups of triplets and 1 pair. minimumRounds += (count / 3) + 1; } } return minimumRounds; } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output for the example cases:
4
-1
Leave a Reply