← Questions

Fit the most tasks into an hour across machine slots

0
AmazonCoding

A coding interview question asked at Amazon. It tests greedy, binary-search and backtracking.

Your team runs a batch cluster of n machines with IDs 0 to n-1. Each machine has m execution slots, so it can run up to m tasks at the same time. A slot runs one task at a time; when a task ends, the slot can start the next one immediately.

You get a list durations of task run times in whole minutes. A task must run on a single slot from start to finish: it cannot be split, paused, or moved. All slots are free at minute 0.

Implement:

def max_tasks(n: int, m: int, durations: list[int], limit: int = 60) -> int:
    ...

Return the largest number of tasks that can finish by minute limit (60 by default). You choose which tasks to run and where.

Constraints

  • 0 <= n, m, and n * m <= 30
  • 0 <= len(durations) <= 40
  • 1 <= durations[i] <= 10^4 (a task longer than limit can never finish)

Example 1

n = 1, m = 1, durations = [10, 20, 30, 40]
-> 3

One slot runs 10, 20 and 30 back to back, ending exactly at minute 60.

Example 2

n = 2, m = 1, durations = [3, 3, 4, 5, 5], limit = 10
-> 5

Machine 0 runs 5 then 5. Machine 1 runs 3, 3 and 4. Placing each shortest task on the least-busy machine finishes only 4, so the order of placement matters.

Be ready to explain whether your method is always optimal.

Clarifying questions

  • Does a task that ends exactly at limit count? (Yes, per the example.)
  • Do machines matter, or only the total number of slots n x m?
  • Are there gaps allowed between tasks on a slot?
  • Is it a problem that this is NP-hard in general, given the small limits?

What a strong answer covers

  • Notes that only the n x m slots matter, each with capacity limit.
  • Shows that if any c tasks fit, the c shortest tasks fit too. So the answer is the largest c for which the c shortest tasks pack into the slots.
  • Checks a given c with backtracking: place tasks longest first, skip slots with the same load, and prune when the remaining time is not enough.
  • Explains, with Example 2, why "shortest task on the least busy slot" is not optimal, and why that does not contradict the "shortest c tasks" rule.
  • Tests no slots, tasks longer than limit, both examples, and a case that fills every slot exactly.

Follow-ups

  • Each task has a value: maximize the total value.
  • Machines run at different speeds.
  • Inputs far beyond 40 tasks: an approximation such as first-fit decreasing, and its guarantee.
  • Return which tasks run on which slot.

Where it's asked

What it tests

greedy · binary-search · backtracking · bin packing

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding