Start learning free

LESSON 248 OF 281 · NESTED LOOPS

Employee of the Year V6 in C++: Top K by Repeated Search

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:

vector<string> names = {"John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"};
vector<int> productivities = {83, 133, 97, 150, 120};
vector<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 vectors 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: vector<bool> taken(names.size(), false);. 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.

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

vector<bool> taken(names.size(), false);
for (int rank = 0; rank < k; rank++) {
    int bestIndex = -1;
    for (int i = 0; i < (int)names.size(); i++) {
        if (!taken[i] && (bestIndex == -1 || productivities[i] > productivities[bestIndex])) {
            bestIndex = i;
        }
    }
    if (bestIndex != -1) {
        taken[bestIndex] = true;
        int bonus = salaries[bestIndex] * 15 / 100;
        cout << names[bestIndex] << ": $" << bonus << endl;
    }
}

STEP 1 OF 9
    Ctrl + Enter to check

    C++ · NESTED LOOPS

    Employee Of The Year V6 in C++, explained

    Problem overview

    This version gives bonuses to the top k most productive employees. Three vectors describe the staff, and index i in all three is the same person: names, productivities and salaries. The variable k is 3 in the starter code. Each bonus is 15% of the salary, rounded down by integer division, and the program prints one line per winner, best first, in the form name: $bonus.

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

    There is no sorting: the program repeats the "find the best employee" search once per winner, and remembers who has already won. The previous version found a single best employee, so this one builds on that search.

    Approach: repeat the search, skip the winners

    The first round looks at everyone and picks the highest productivity. The second round does the same, but ignores the winner of round one, so it finds the second best. The third round ignores both earlier winners. After k rounds you have the top k, in order.

    To ignore earlier winners, the program keeps a vector<bool> called taken, with one flag per employee. A true flag means that employee has already won. This is nested looping: an outer loop over the rounds and an inner loop over the employees.

    Two rules shape the inner search. Ties go to the employee listed first, so the comparison is strictly greater: a later employee with the same productivity doesn't replace the current best. And if k is larger than the number of employees, the late rounds find nobody and must print nothing.

    Step by step

    1. Create taken with vector<bool> taken(names.size(), false). The first argument is the number of flags and the second is the value of each one, so nobody has won yet.
    2. Write the outer loop with rank from 0 while rank < k. The counter only counts rounds, once per winner.
    3. Start each round with int bestIndex = -1;. The value -1 means "nobody chosen yet", because no employee has that index. Declared inside the outer loop, it resets in every round.
    4. Write the inner loop over every employee, i from 0 while i < (int)names.size().
    5. Update the best. Inside the inner loop, an if requires that employee i is not taken, and that either bestIndex is -1 or the productivity of i is strictly greater than that of bestIndex. Then it sets bestIndex = i.
    6. Check that someone was found after the inner loop: bestIndex != -1. If everybody has won already, the round must do nothing.
    7. Mark the winner as taken straight away, so the next round skips them.
    8. Compute the bonus: salaries[bestIndex] * 15 / 100.
    9. Print names[bestIndex], then ": $", then the bonus.

    The solution in C++

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

    Here is how the rounds go with the starter data:

    round (rank)candidates leftbestprinted
    0all fiveAlice Chen (150)Alice Chen: $37500
    1all but AliceMary Jane (133)Mary Jane: $50250
    2all but Alice and MaryCarlos Diaz (120)Carlos Diaz: $27000

    The condition in step 5 relies on short-circuit evaluation. In bestIndex == -1 || productivities[i] > productivities[bestIndex], the second part is only evaluated when the first is false. So productivities[-1] is never read. If the order were swapped, the program would read outside the vector in the first comparison of every round.

    The vector<bool> is a specialised container that packs its flags into bits, but for this use you can treat it like any other vector of flags: taken[i] reads one, and taken[bestIndex] = true sets one.

    Edge cases and common mistakes

    • A larger k. With k = 7 and five employees, the program prints five lines: after Alice, Mary and Carlos come Bob Smith with $31500 and John Doe with $20250. Rounds 6 and 7 find nobody. Without the bestIndex != -1 check, taken[-1] would be written, which is undefined behaviour.
    • A smaller k. With k = 1 only Alice Chen is printed. The code uses k everywhere, so it works for any value.
    • Ties. With the strict >, two employees with the same productivity are ranked in the order they are listed. Using >= would let the later one win.
    • Forgetting to mark the winner. Without taken[bestIndex] = true, every round would find Alice again.
    • Putting bestIndex outside the outer loop. The old winner's index would carry into the next round.
    • Bonus arithmetic. Multiply by 15 before dividing by 100. Salaries up to 335000 times 15 stay well inside an int.

    Complexity

    The outer loop runs k times and the inner loop runs once per employee, so the time is O(k × n) for n employees. When k is small this is fast, and for the full ranking it grows like n squared. The extra space is the taken vector, which is O(n).

    Testing

    With the starter data and k = 3, the output is the three lines at the top. With k = 1 it is only the first line. With k = 7 it is five lines, ending with Bob Smith and John Doe.

    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