Start learning free

LESSON 183 OF 667 · LOOPING OVER ARRAY INDICES

Employee Of The Year V5 in C++: Top Two Employees with Two Loops

Practice Read the full explanation

Hand out bonuses to the top 2 most productive employees: the best one first, then the second best. You don't need any sorting. Find the best employee with the loop from v4, then find the best of the other employees with a second loop.

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};

Build:

Alice Chen: $37500
Mary Jane: $50250

Rules:

  • Index i in all three vectors refers to the same employee.
  • The best employee is the one with the highest productivity; the second best is the one with the highest productivity among all the other employees.
  • 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 two lines, the best employee first: name: $bonus.

Find the best employee first, exactly as in v4. Remember: strictly greater, so the first listed wins a tie.

For the second place, loop over all the indices and ignore the best one. The whole condition is if (i != bestIndex && (secondIndex == -1 || productivities[i] > productivities[secondIndex])) {. "Nobody chosen yet" must also let an employee in.

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 bestIndex = 0;
for (int i = 1; i < (int)names.size(); i++) {
    if (productivities[i] > productivities[bestIndex]) {
        bestIndex = i;
    }
}
int secondIndex = -1;
for (int i = 0; i < (int)names.size(); i++) {
    if (i != bestIndex && (secondIndex == -1 || productivities[i] > productivities[secondIndex])) {
        secondIndex = i;
    }
}
int bestBonus = salaries[bestIndex] * 15 / 100;
int secondBonus = salaries[secondIndex] * 15 / 100;
cout << names[bestIndex] << ": $" << bestBonus << endl;
cout << names[secondIndex] << ": $" << secondBonus << endl;

STEP 1 OF 10
    Ctrl + Enter to check

    C++ · LOOPING OVER ARRAY INDICES

    Employee Of The Year V5 in C++, explained

    Problem overview

    This version hands out bonuses to the two most productive employees, the best first and the second best after. The data is the same three parallel vectors as before: names, productivities and salaries, where index i in each describes one employee. The second best is the employee with the highest productivity among all the others. When productivities tie, the employee listed first ranks higher. Each bonus is 15% of the salary, rounded down, and each line is printed as name: $bonus.

    With the starter data, Alice Chen has 150 and Mary Jane has 133, so the output is:

    Alice Chen: $37500
    Mary Jane: $50250
    

    Note that the second line has the larger bonus. The ranking is by productivity, not by bonus, and Mary Jane's salary is higher than Alice Chen's.

    Approach: find the best, then find the best of the rest

    The previous version found the best employee with one scan. There is no need to sort for the top two. After the first scan, run a second scan that ignores the winner: whoever has the highest productivity among everyone else is second.

    The second scan needs a starting point. In the first scan, employee 0 served as the initial best, but here employee 0 might be the overall winner and therefore not allowed. So secondIndex starts at -1, a value that is not a valid index and so can mean "nobody chosen yet". The condition for taking over has two parts: the candidate is not the best employee, and either nobody is chosen yet or the candidate's productivity is strictly greater than that of the current second.

    The strict comparison keeps the tie rule. When two employees tie for second place, the first listed is chosen first and is never replaced by a later one with the same productivity.

    Step by step

    1. Create bestIndex at 0. It is the best employee known so far.
    2. Write the first loop with i from 1 while i < (int)names.size(). Employee 0 is already the best candidate.
    3. Update bestIndex when productivities[i] is strictly greater than productivities[bestIndex].
    4. Create secondIndex at -1. No employee has that index, so it means nobody is second yet.
    5. Write the second loop with i starting at 0. The best employee could be anywhere in the list, including at index 0, so this loop begins at the start and skips the best employee inside the body.
    6. Test each candidate. The if requires i != bestIndex and also requires that either secondIndex == -1 or productivities[i] > productivities[secondIndex]. When both hold, set secondIndex to i.
    7. Compute bestBonus as salaries[bestIndex] * 15 / 100.
    8. Compute secondBonus the same way from secondIndex.
    9. Print the best employee as the name, a colon, a dollar sign and the bonus.
    10. Print the second best in the same form on the next line.

    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 bestIndex = 0;
    for (int i = 1; i < (int)names.size(); i++) {
        if (productivities[i] > productivities[bestIndex]) {
            bestIndex = i;
        }
    }
    int secondIndex = -1;
    for (int i = 0; i < (int)names.size(); i++) {
        if (i != bestIndex && (secondIndex == -1 || productivities[i] > productivities[secondIndex])) {
            secondIndex = i;
        }
    }
    int bestBonus = salaries[bestIndex] * 15 / 100;
    int secondBonus = salaries[secondIndex] * 15 / 100;
    cout << names[bestIndex] << ": $" << bestBonus << endl;
    cout << names[secondIndex] << ": $" << secondBonus << endl;
    

    Details worth a closer look:

    • Order inside the condition. In secondIndex == -1 || productivities[i] > productivities[secondIndex], the left side is checked first. When it is true, the || operator skips the right side, so productivities[-1] is never evaluated. If you swapped the two parts, the first candidate would read the vector at index -1, which is undefined behaviour.
    • Precedence. && binds tighter than ||, so the parentheses around the || part are needed. Without them, the condition would mean something different: employee i != bestIndex and nobody chosen, or the productivity test, which could pick the best employee.
    • The second loop reuses i. Each for declares its own i, which exists only inside that loop, so the two loops don't conflict.

    Complexity

    There are two passes over the n employees, so the time is O(n), and the extra space is O(1). Sorting would cost O(n log n) and is not needed for two results.

    Edge cases and common mistakes

    • Everyone tied. With names X, Y, Z, productivities 9, 9, 9 and salaries 100, 200, 300, X is best because no later employee is strictly greater. In the second loop X is skipped, Y is chosen because secondIndex is -1, and Z does not replace Y. The output is X: $15 and Y: $30.
    • The best employee listed last. With productivities 1, 5 and 9, the best is at index 2. The second loop picks index 1. The output is Z: $45 then Y: $30.
    • Tie for best. With X, Y, Z at productivities 3, 9 and 9, the best is Y, the first of the two. Z, with the same productivity, is second.
    • Fewer than two employees. With one employee, the second loop never finds a candidate, so secondIndex stays -1 and names[secondIndex] reads outside the vector, which is undefined behaviour. The lesson's data has several employees; a general version would check the size first.
    • Starting the second loop at 1. That would skip employee 0, who may be the second best.
    • Forgetting the strict >. >= would let a later tied employee replace an earlier one.

    Testing

    InputOutput
    the starter dataAlice Chen: $37500, then Mary Jane: $50250
    X, Y, Z with productivities 9, 9, 9 and salaries 100, 200, 300X: $15, then Y: $30
    X, Y with productivities 3, 8 and salaries 1000, 2000Y: $300, then X: $150
    X, Y, Z with productivities 1, 5, 9 and salaries 100, 200, 300Z: $45, then Y: $30
    Keep going with C++650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free