Skip to the content

Not one more, not one less

Problem

The company is splitting 5000 of the year's profits among all its people, Carol included, in proportion to monthly salary. It's paid in whole units, and rounding each person's share doesn't work: the nine rounded shares add up to 5001.

Accounting does it this way. Each person gets their share with the decimals cut off. The units left over are handed out one at a time, starting with whoever lost the biggest fraction; between two equal fractions, whoever comes first alphabetically goes first. Paige's share is 729.54: she has 729 for sure and waits her turn with her .54.

Show each person's name and what they get, in that order, from whoever gets the most to whoever gets the least and, on a tie, by name. The total has to come to exactly 5000, with these salaries and with whatever the salaries are tomorrow.

What it has to return

These rows, in this order

namepayout
Carol925
Paige729
Mark676
Lydia534
Samuel534
Frank463
Grace427
Nicole374
Rachel338

This is what comes out with the data in the practice database this challenge uses. The column names don’t count, so name yours however you like: what counts is how many there are and the order they come in. Besides this one, the challenge has hidden tests with other data that are revealed when you submit your solution.

You start with this

SQL

SELECT name, salary,
  SUM(salary) OVER () AS total
FROM employees
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(2ⁿ) challenges

See all challenges →