Problem overview
The company gives a bonus to the k most productive employees. Three arrays describe the staff, and index i in all three belongs to the same person: names[i], productivities[i] and salaries[i]. The constant k says how many winners there are, and the code has to keep working when k changes.
A winner's bonus is 15% of the salary, rounded down. The program prints one line per winner, best first, in the form name: $bonus. There is no sorting in this version: the search for the best employee is repeated k times, and each round skips the people who already won.
For the starting data and k = 3, the three most productive employees are Alice Chen (150), Mary Jane (133) and Carlos Diaz (120):
Alice Chen: $37500
Mary Jane: $50250
Carlos Diaz: $27000
Bob Smith (97) and John Doe (83) are less productive than the three winners, so they get nothing.
Approach: repeat the search, remembering the winners
Finding the single best employee is a running maximum: scan everyone, keep the index of the best so far, replace it only on a strictly greater productivity. Doing that k times would find the same person every time, unless the winners are removed from the search.
The program doesn't remove anyone. It marks them. A boolean array taken has one entry per employee, all false at first, and a winner's entry becomes true. Inside the search, a taken employee is skipped, so round 2 finds the best of the rest, round 3 the best of those still left, and so on.
That gives two nested loops. The outer loop counts the rounds, once per winner. The inner loop scans all the employees in one round.
The search starts each round with bestIndex equal to -1, which can't be a real index and so means nobody has been chosen yet. The test for a new best is "not taken, and either nobody is chosen yet or strictly more productive than the current best". The first untaken employee always passes through the -1 case, and later ones have to beat the current best.
The strictness gives the tie rule for free: when two employees have the same productivity, the one listed first is reached first and keeps the lead.
With the starting data, the rounds go like this:
| Round | Best among those not taken | Productivity |
|---|---|---|
| 0 | Alice Chen | 150 |
| 1 | Mary Jane | 133 |
| 2 | Carlos Diaz | 120 |
Step by step
- Create the flags.
takenis aboolean[]built withnew Array(names.length).fill(false): an array as long as the staff, withfalsein every slot. - Write the outer loop.
rankcounts from 0 while it is belowk, once per winner. The counter only counts rounds, and the loop body is one full search. - Reset the best at the start of each round. Inside the outer loop,
let bestIndex: number = -1. Declared here, it starts again with nobody chosen every round. - Write the inner loop.
iruns over every employee, because every round looks at everybody again. - Test each employee. The
ifrequires!taken[i]and eitherbestIndex === -1orproductivities[i] > productivities[bestIndex]. When it holds, setbestIndextoi. - Check that someone was found after the inner loop:
bestIndex !== -1. Whenkis larger than the number of employees, the last rounds find nobody and must print nothing. - Mark the winner by setting
taken[bestIndex]totrueright away, because the next round reads it. - Compute the bonus. A
constnamedbonus:Math.floor(salaries[bestIndex] * 15 / 100). Multiplying first and dividing after keeps the arithmetic simple, andMath.floordrops any fraction. - Print the winner as
names[bestIndex],": $"andbonus, joined with+. The name and the bonus both come from the winner's index.
The solution in TypeScript
const names: string[] = ["John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"];
const productivities: number[] = [83, 133, 97, 150, 120];
const salaries: number[] = [135000, 335000, 210000, 250000, 180000];
const k: number = 3;
const taken: boolean[] = new Array(names.length).fill(false);
for (let rank: number = 0; rank < k; rank++) {
let bestIndex: number = -1;
for (let i: number = 0; i < names.length; i++) {
if (!taken[i] && (bestIndex === -1 || productivities[i] > productivities[bestIndex])) {
bestIndex = i;
}
}
if (bestIndex !== -1) {
taken[bestIndex] = true;
const bonus: number = Math.floor(salaries[bestIndex] * 15 / 100);
console.log(names[bestIndex] + ": $" + bonus);
}
}
Details worth knowing:
new Array(n).fill(false).new Array(5)alone creates an array of length 5 with empty slots, andfill(false)writesfalseinto every one. The annotationboolean[]describes the result for the compiler and is erased at run time.===and!==. They compare without converting types, which is the usual choice in TypeScript.- Short-circuit evaluation.
&&and||stop as soon as the result is known. InbestIndex === -1 || productivities[i] > productivities[bestIndex]the right side is never evaluated whilebestIndexis-1. - The
$in the string. In": $", an ordinary double-quoted string, the dollar sign is just a character. Only inside backtick template strings does$followed by{start an expression. - A
constinside the loop.bonusis created fresh on every pass of theifblock, which is allowed because each pass has its own scope.
Complexity
Time: O(k * n). Each of the k rounds scans all n employees once, with constant work per employee. When k is close to n, that approaches O(n²). A sort would take O(n log n), but this lesson deliberately repeats the search.
Space: O(n). The taken array has one entry per employee. Everything else is a few variables.
Edge cases and common mistakes
- Different values of
k. Withk = 1only Alice Chen is printed. Withk = 2it is Alice Chen and Mary Jane. Withk = 5everybody is printed, adding Bob Smith ($31500) and John Doe ($20250). klarger than the staff. Withk = 7the output is the same five lines as fork = 5. Rounds 6 and 7 find nobody, and the check onbestIndexkeeps them silent.- Removing the check. Without the
bestIndex !== -1check and withk = 7, two extra lines appear:undefined: $NaN. An index of-1readsundefinedfrom an array, and the arithmetic on it givesNaN. There is no error, only wrong output. k = 0. The outer loop never runs and the program prints nothing.- Ties. Suppose the productivities are
[100, 150, 150, 90, 150]. The three employees with 150 win in list order: Mary Jane, Bob Smith, then Carlos Diaz. Writing>=instead of>reverses that order, printing Carlos Diaz first. - Leaving out the
bestIndex === -1case. If the test is only!taken[i] && productivities[i] > productivities[bestIndex], comparing againstproductivities[-1](undefined) is always false, so no one is ever chosen and the program prints nothing. - Not marking the winner. Without setting
taken[bestIndex]to true, every round picks the same employee again.
Testing
- The starting data with
k = 1printsAlice Chen: $37500. - With
k = 2it printsAlice Chen: $37500andMary Jane: $50250. - With
k = 5it addsBob Smith: $31500andJohn Doe: $20250after Carlos Diaz. - With
k = 7the output equalsk = 5. - With
k = 0there is no output.
