Start learning free

LESSON 252 OF 289 · NESTED LOOPS

Employee of the Year V6 in C#: Top K with Nested Loops

Practice Read the full explanation

Generalize the previous version: give bonuses to the top K most productive employees, where k is given as a variable. Still no sorting: repeat the search for the best employee k times, and remember who already won so nobody wins twice.

You start with:

        string[] names = {"John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"};
        int[] productivities = {83, 133, 97, 150, 120};
        int[] salaries = {135000, 335000, 210000, 250000, 180000};
        int k = 3;

Build:

Alice Chen: $37500
Mary Jane: $50250
Carlos Diaz: $27000

Rules:

  • Index i in all three arrays refers to the same employee.
  • Round 1 finds the employee with the highest productivity, round 2 the best among the employees who have not won yet, and so on, for k rounds.
  • If two employees have the same productivity, the one listed first wins.
  • Each bonus is 15% of the salary, rounded down (with integer division).
  • Print one line per winner, best first: name: $bonus.
  • If k is larger than the number of employees, everybody wins once and you print one line per employee: when nobody is left, a round prints nothing.
  • Your code must keep working when k changes to 1, 2, 5 or 7.

Use a list of booleans: bool[] taken = new bool[names.Length];. A round finds the best employee among those who are not taken yet, then marks that employee as taken.

The outer loop runs k times and the inner loop is the search from v4 with one more condition: if (!taken[i] && (bestIndex == -1 || productivities[i] > productivities[bestIndex])) {. If nobody is found in a round, skip the rest of that round.

        string[] names = {"John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"};
        int[] productivities = {83, 133, 97, 150, 120};
        int[] salaries = {135000, 335000, 210000, 250000, 180000};
        int k = 3;

        bool[] taken = new bool[names.Length];
        for (int rank = 0; rank < k; rank++) {
            int bestIndex = -1;
            for (int i = 0; i < names.Length; i++) {
                if (!taken[i] && (bestIndex == -1 || productivities[i] > productivities[bestIndex])) {
                    bestIndex = i;
                }
            }
            if (bestIndex != -1) {
                taken[bestIndex] = true;
                int bonus = salaries[bestIndex] * 15 / 100;
                Console.WriteLine(names[bestIndex] + ": $" + bonus);
            }
        }

STEP 1 OF 9
    Ctrl + Enter to check

    C# · NESTED LOOPS

    Employee Of The Year V6 in C#, explained

    Problem overview

    The company gives bonuses to its k most productive employees, and k is a variable. Three parallel arrays describe the staff, and index i in all of them refers to the same person: names, productivities and salaries. The bonus is 15% of the salary, rounded down. The program prints one line per winner, best first, in the form name: $bonus, and it does not sort anything. Instead, it repeats the search for the most productive employee k times, skipping everybody who has already won.

    With the starting data and k = 3 the output is:

    Alice Chen: $37500
    Mary Jane: $50250
    Carlos Diaz: $27000

    Alice has the highest productivity, 150, and her salary is 250000, so her bonus is 250000 * 15 / 100 = 37500. Mary is next with 133, and Carlos third with 120.

    Approach: search k times, remembering the winners

    A search for the best element is a loop with a "best so far" variable. Here that variable is an index, bestIndex, which starts at -1. No employee has index -1, so it means that nobody has been chosen yet. Each employee is compared with the current best, and replaces it only when their productivity is strictly greater. Strictly greater matters for ties: an employee who equals the current best does not replace them, so the one listed first wins.

    To get the second best, the search must ignore the first winner. A bool array named taken, with one slot per employee, records who has already won. The search considers only employees whose slot is still false. After each round, the winner's slot is set to true, so the next round finds the best among the rest.

    This is a nested loop: the outer loop counts the rounds, one for each winner, and the inner loop looks at every employee in each round. For 5 employees and k = 3 the inner body runs 15 times. The work grows as k times n, which is fine for small data and avoids the need to sort the arrays.

    The last piece is the case where k is larger than the number of employees. Then some rounds find nobody: every slot of taken is true and bestIndex stays at -1. Those rounds must print nothing, so the winner handling sits inside an if (bestIndex != -1) check.

    Step by step

    1. Create taken with new bool[names.Length]. C# starts every bool slot of a new array as false, which is right: nobody has won yet.
    2. Write the outer loop with rank counting from 0 while rank < k. The counter only counts the rounds, once per winner, and is not printed.
    3. Create bestIndex at -1 inside the round. Declaring it inside the outer loop means each round starts again with nobody chosen.
    4. Write the inner loop over i from 0 to names.Length. Every round looks at every employee again.
    5. Test each candidate. The employee must not have won (!taken[i]) and either nobody is chosen yet (bestIndex == -1) or the productivity is strictly greater than that of bestIndex. When it holds, set bestIndex = i.
    6. Check that someone was found. After the inner loop, test bestIndex != -1. This guards the next steps when k is too large.
    7. Mark the winner with taken[bestIndex] = true;, immediately, since the next round reads it.
    8. Compute the bonus as salaries[bestIndex] * 15 / 100. Multiplying first and dividing second, with integers, rounds down.
    9. Print the winner as the name at bestIndex, then ": $" and the bonus. The + operator turns the number into text when it joins it to a string.

    The solution in C#

            string[] names = {"John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"};
            int[] productivities = {83, 133, 97, 150, 120};
            int[] salaries = {135000, 335000, 210000, 250000, 180000};
            int k = 3;
    
            bool[] taken = new bool[names.Length];
            for (int rank = 0; rank < k; rank++) {
                int bestIndex = -1;
                for (int i = 0; i < names.Length; i++) {
                    if (!taken[i] && (bestIndex == -1 || productivities[i] > productivities[bestIndex])) {
                        bestIndex = i;
                    }
                }
                if (bestIndex != -1) {
                    taken[bestIndex] = true;
                    int bonus = salaries[bestIndex] * 15 / 100;
                    Console.WriteLine(names[bestIndex] + ": $" + bonus);
                }
            }
    

    Details worth knowing:

    • Short-circuit operators. && and || stop as soon as the answer is known. In bestIndex == -1 || productivities[i] > productivities[bestIndex], when bestIndex is -1 the right side is never evaluated. That matters: productivities[-1] would throw an IndexOutOfRangeException with the message "Index was outside the bounds of the array."
    • Parentheses in the condition. && binds tighter than ||. The parentheses make !taken[i] apply to the whole test, so a taken employee can never be chosen, whatever the productivity.
    • Arrays are fixed-size. The taken array has exactly one slot per employee and cannot change length. It is indexed with the same i as the other three arrays.
    • The dollar sign is plain text. In ": $" the $ is just a character. It has a special meaning only in front of the opening quote, as in $"...", which starts an interpolated string.
    • int overflow. int arithmetic wraps silently at about 2.1 billion. The product salaries[bestIndex] * 15 overflows for salaries above 143165576. A salary of 150000000 gives the line X: $-20449672 for an employee called X. The lesson's salaries are far below that limit.

    Edge cases and common mistakes

    • Different values of k. For the starting data, k = 1 prints only Alice, and k = 2 prints Alice and Mary. With k = 5 every employee wins once, in the order Alice, Mary, Carlos, Bob and John, whose bonuses are 37500, 50250, 27000, 31500 and 20250.
    • k larger than the staff. With k = 7 the output is the same five lines as for 5. The two extra rounds find nobody and print nothing, thanks to the -1 check. Without it, taken[-1] would throw.
    • k = 0. The outer loop never runs and nothing is printed.
    • Ties. With productivities 100, 100 and 90 for employees A, B and C, the order is A, B, C. A tie keeps the earlier employee because the comparison is strictly greater. Using >= would make the later employee replace the earlier one.
    • Forgetting to mark the winner. Without taken[bestIndex] = true, every round would pick the same employee, and the same line would print k times.
    • Declaring bestIndex outside the outer loop. It would keep the previous winner's index into the next round, which then compares everyone against that winner instead of starting with nobody chosen, and the output would be wrong.

    Testing

    • The starting data with k = 3 prints Alice Chen $37500, Mary Jane $50250 and Carlos Diaz $27000.
    • With k = 1 only Alice Chen: $37500 prints.
    • With k = 7 five lines print, ending with John Doe: $20250.
    • Employees A, B and C with productivities 100, 100 and 90, salaries 1000, 2000 and 3000 and k = 3 print A: $150, B: $300 and C: $450.
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free