Minimize time for two handlers
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Take-home Project
You are given a sequence of jobs that must be processed in the given order. There are exactly two handlers, and each job must be assigned to one of them.
Each job has a **type**. Let `workList[i]` be the type of the `i`-th job. For each job type `t`, you are also given:
- `longPrepTime[t]`: the cost for a handler to process type `t` if this is the first job that handler has ever processed, or if the handler's most recent job type is different from `t`
- `shortPrepTime[t]`: the cost for a handler to process type `t` if the handler's most recent job type is also `t`
Initially, both handlers have processed nothing.
Your task is to assign every job in `workList` to one of the two handlers so that the **total preparation time** is minimized.
Example:
- `workList = [1, 2, 2]`
- `longPrepTime = [4, 5]`
- `shortPrepTime = [2, 3]`
Assume job types are 1-indexed, so:
- type `1` has `longPrepTime = 4`, `shortPrepTime = 2`
- type `2` has `longPrepTime = 5`, `shortPrepTime = 3`
One optimal assignment is:
- handler A processes job type `1` with cost `4`
- handler B processes job type `2` with cost `5`
- handler B processes job type `2` again with cost `3`
So the minimum total time is `12`.
Return the minimum total preparation time.
Quick Answer: This question evaluates algorithmic optimization skills and stateful scheduling reasoning, focusing on task assignment trade-offs and cumulative cost minimization for two handlers.
Part 1: Minimum Preparation Time for Two Handlers
You are given a list of jobs in the exact order they must be assigned. Each value in workList is a work type ID from 1 to m. There are exactly two handlers, and each job must be assigned to one of them.
When a handler processes a job of type x:
- If it is the first job ever assigned to that handler, or the handler's previous job type is different from x, the cost is longPrepTime[x - 1].
- If the handler's previous job type is also x, the cost is shortPrepTime[x - 1].
Return the minimum total preparation time needed to assign all jobs.
Constraints
- 0 <= len(workList) <= 200
- 0 <= len(longPrepTime) == len(shortPrepTime) <= 50
- If workList is non-empty, every work type x satisfies 1 <= x <= len(longPrepTime)
- 0 <= longPrepTime[i], shortPrepTime[i] <= 10^4
Examples
Input: ([1, 2, 2], [4, 5], [2, 3])
Expected Output:
Explanation: Assign work 1 to handler A for 4, work 2 to handler B for 5, and the last work 2 again to handler B for 3. Total = 12.