I have a question regarding Question 13.12 (page 208) in the book Elements of Programming Interviews by Adnan, Tsung-Hsien and Amit.
The question:
ABC corporation needs to cut payroll expenses to a specified target. The chief executive officer wants to do this by putting a cap on last year's salaries. Every employee who earned more than the cap last year will be paid the cap this year; employees who earned no more than the cap will see no change in their salary.
For example, if there were five employees with salaries last year were $90, $30, $100, $40, and $20, and the target payroll this year is $210, then $60 is suitable salary cap, since 60+30+60+40+20=210.
Design an algorithm for computing the salary cap, given the existing salaries and the targeted payroll.
Textbook solution:
def find_salary_cap(target_payroll, current_salaries):
current_salaries.sort()
unadjusted_salary_sum = 0.0
for i, current_salary in enumerate(current_salaries):
adjusted_people = len(current_salaries) - i
adjusted_salary_sum = current_salary * adjusted_people
if unadjusted_salary_sum + adjusted_salary_sum >= target_payroll:
return (target_payroll - unadjusted_salary_sum) / adjusted_people
unadjusted_salary_sum += current_salary
# No solution, since target_payroll > existing payroll.
return -1.0
Follow-up question: Can you solve the same problem using only O(1) space.
My question:
Isn't the textbook solution already using O(1) space?