Maximize optional tasks under daily limit
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Online Assessment
Overview: This question evaluates algorithmic problem-solving in scheduling and combinatorial optimization, assessing understanding of capacity-constrained assignment, greedy or matching strategies, and correctness and complexity reasoning.
Constraints
- 1 <= n <= 10^5 (n may be 0 if both arrays are empty)
- 1 <= limit <= 10^9
- 0 <= required[i], optional[i] <= 10^9
- len(required) == len(optional) == n
- If required[i] >= limit, day i cannot hold any optional task
Examples
Input: (7, [4, 5, 2, 4], [5, 6, 3, 4])
Expected Output: (2, [3, -1, 4, -1])
Explanation: Prompt example. Slacks: day0=3, day1=2, day2=5, day3=3. Processing tightest-first, day1(2) fits nothing unused that helps, day0(3) takes optional 3, day3(3) finds no remaining fit, day2(5) takes optional 4. Max = 2.
Input: (7, [7, 7, 7], [1, 2, 3])
Expected Output: (0, [-1, -1, -1])
Explanation: Every day's required equals limit, so slack is 0 everywhere and no optional task fits.
Hints
- Each day independently offers `limit - required[i]` units of free slack; an optional task only fits if its cost is <= that slack. The day's required cost is fixed and unavoidable.
- This reduces to a bipartite matching: optional task fits day iff cost <= slack. Because both sides are one-dimensional thresholds, sorting beats general matching.
- Sort the day slacks ascending and the optional costs ascending. Walk the days from tightest to loosest and assign each the cheapest still-unused optional that fits — an exchange argument shows this never reduces the achievable count.
- Follow-up — optional[i] tied to day i: it becomes n independent yes/no checks (`optional[i] <= limit - required[i]`); no sorting or matching needed.
- Follow-up — required[i] > limit: that day is infeasible for its own required task; either report it as impossible or treat its optional slack as 0 (it can hold nothing). Follow-up — up to k optional per day: give each day k slots and run the same sorted-greedy, filling the smallest fitting optional tasks into the tightest available slots.