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
- Create
taken.new boolean[names.length]makes one slot per employee, and Java starts everybooleanslot asfalse, which means nobody has won yet. - Write the outer loop.
rankgoes from 0 whilerank < k, one pass per winner. The counter only counts rounds, and its value isn't used inside the loop. - Reset
bestIndex. Inside the round,int bestIndex = -1;declares the variable, so each round starts with nobody chosen. - Write the inner loop.
ivisits every employee, from 0 up tonames.length. - 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. ThenbestIndexbecomesi. The comparison is strict, so on a tie the first employee in the list keeps the place. - Check that someone was found. After the inner loop,
bestIndex != -1tells whether the round found anybody. Whenkis larger than the staff, the late rounds find nobody and must print nothing. - Mark the winner. Set
taken[bestIndex]totrue, so later rounds skip this person. The change has to happen right away, because the next round reads it. - Compute the bonus.
salaries[bestIndex] * 15 / 100multiplies first and divides second, so the integer division rounds down. - 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. WhenbestIndexis -1 the right side, which would readproductivities[-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 withfalse, a newint[]with 0. Local variables such asbestIndexhave no default, and that is why it is assigned at once. - Integer arithmetic.
salaries[bestIndex] * 15 / 100stays inint. 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 = 1prints only Alice Chen. Withk = 5ork = 7all five employees print, in the order Alice Chen, Mary Jane, Carlos Diaz, Bob Smith, John Doe. Withk = 0nothing prints. - Too many rounds. Without the
bestIndex != -1check, a round with nobody left uses -1 as an index and throwsArrayIndexOutOfBoundsException: 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
bestIndexoutside 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
takenis 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 * 15overflowsintand the bonus comes out as -647710. The lesson's salaries are far smaller, but for huge values15Lmakes the arithmetic uselong.
Testing
k = 1printsAlice Chen: $37500.k = 2printsAlice Chen: $37500andMary Jane: $50250.k = 5prints five lines, the last two beingBob Smith: $31500andJohn Doe: $20250.k = 7prints the same five lines ask = 5.
