Start learning free

LESSON 250 OF 671 · NESTED LOOPS

Employee of the Year V6 in Java: 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: boolean[] taken = new boolean[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;

boolean[] taken = new boolean[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;
        System.out.println(names[bestIndex] + ": $" + bonus);
    }
}

STEP 1 OF 9
    Ctrl + Enter to check

    JAVA · NESTED LOOPS

    Employee Of The Year V6 in Java, explained

    Problem overview

    The company gives bonuses to the k most productive employees. Three arrays describe the staff, and index i in all three refers to the same person: names, productivities and salaries. A bonus is 15% of the salary, rounded down. The program prints one line per winner, best first, in the form name: $bonus.

    With k = 3 and the starting data, the winners are Alice Chen (productivity 150), Mary Jane (133) and Carlos Diaz (120):

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

    The code can't sort the arrays. It must repeat a search for the best employee k times, and remember who has already won so that nobody wins twice. If two employees have the same productivity, the one listed first wins. If k is larger than the number of employees, everybody wins once and the extra rounds print nothing.

    Approach: repeat the search, skip the winners

    Finding the single best employee is a loop with a "best so far" variable. To find the top three without sorting, run that search three times. The second search must ignore the first winner, and the third must ignore both earlier winners. A boolean array called taken records this: taken[i] is true once employee i has won.

    The result is two nested loops. The outer loop counts the rounds, one per winner. The inner loop is the search over all employees. Every round starts again from nothing found, looks at everyone who isn't taken, and keeps the one with the highest productivity.

    The search keeps an index, bestIndex, not the productivity value, because the name and the salary of the winner are needed later and are found through the index. The value -1 means "nobody chosen yet". It is a safe marker, because no employee has the index -1.

    Step by step

    1. Create taken. new boolean[names.length] makes one slot per employee, and Java starts every boolean slot as false, which means nobody has won yet.
    2. Write the outer loop. rank goes from 0 while rank < k, one pass per winner. The counter only counts rounds, and its value isn't used inside the loop.
    3. Reset bestIndex. Inside the round, int bestIndex = -1; declares the variable, so each round starts with nobody chosen.
    4. Write the inner loop. i visits every employee, from 0 up to names.length.
    5. Test each candidate. An employee becomes the round's best when they are not taken, and either nobody is chosen yet or their productivity is strictly greater than that of bestIndex. Then bestIndex becomes i. The comparison is strict, so on a tie the first employee in the list keeps the place.
    6. Check that someone was found. After the inner loop, bestIndex != -1 tells whether the round found anybody. When k is larger than the staff, the late rounds find nobody and must print nothing.
    7. Mark the winner. Set taken[bestIndex] to true, so later rounds skip this person. The change has to happen right away, because the next round reads it.
    8. Compute the bonus. salaries[bestIndex] * 15 / 100 multiplies first and divides second, so the integer division rounds down.
    9. Print the winner. The name and the salary share the winner's index. The + joins the name, the text ": $" and the number.

    The solution in Java

    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;
    
    boolean[] taken = new boolean[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;
            System.out.println(names[bestIndex] + ": $" + bonus);
        }
    }
    

    The Java details worth a closer look:

    • Short-circuit evaluation. In bestIndex == -1 || productivities[i] > productivities[bestIndex], the || stops as soon as its left side is true. When bestIndex is -1 the right side, which would read productivities[-1], never runs. The order of the two conditions is therefore part of the logic.
    • Parentheses around the ||. The operator && binds tighter than ||. The parentheses make the !taken[i] test apply to both alternatives.
    • Default values. A new boolean[] is filled with false, a new int[] with 0. Local variables such as bestIndex have no default, and that is why it is assigned at once.
    • Integer arithmetic. salaries[bestIndex] * 15 / 100 stays in int. For 335000 it is 50250 exactly, and for any salary it rounds down.

    Complexity

    Time: O(k * n) for n employees. Each of the k rounds scans all n employees once. When k is as large as n, this is O(n²). Sorting would get all the winners in O(n log n), but this lesson practises nested loops.

    Space: O(n) for the taken array, plus a few variables.

    Edge cases and common mistakes

    • Different values of k. With the starting data, k = 1 prints only Alice Chen. With k = 5 or k = 7 all five employees print, in the order Alice Chen, Mary Jane, Carlos Diaz, Bob Smith, John Doe. With k = 0 nothing prints.
    • Too many rounds. Without the bestIndex != -1 check, a round with nobody left uses -1 as an index and throws ArrayIndexOutOfBoundsException: Index -1 out of bounds.
    • Ties. With productivities 83, 150, 97, 150 and 120, the two employees with 150 are Mary Jane and Alice Chen, and Mary Jane comes first in the output, as she is listed first. A >= comparison would give the tie to the later employee.
    • Everyone equal. When all productivities are 100, the output follows the list order from John Doe to Carlos Diaz.
    • Declaring bestIndex outside the outer loop. It would keep the previous winner's index, and the next round would compare against it. It must be reset inside the round.
    • Forgetting to mark the winner. If taken is never updated, every round finds the same person and prints Alice Chen k times.
    • Overflow. The multiplication happens before the division. With a salary of 2,000,000,000, salary * 15 overflows int and the bonus comes out as -647710. The lesson's salaries are far smaller, but for huge values 15L makes the arithmetic use long.

    Testing

    • k = 1 prints Alice Chen: $37500.
    • k = 2 prints Alice Chen: $37500 and Mary Jane: $50250.
    • k = 5 prints five lines, the last two being Bob Smith: $31500 and John Doe: $20250.
    • k = 7 prints the same five lines as k = 5.
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free