Minimum starting battery for a task queue
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Amazon. It tests prefix sums, arrays and greedy.
A server runs a queue of jobs strictly in order, powered by one battery. Job i changes the battery by -usage[i]: a positive usage[i] drains the battery, and a negative one means the job recharges it (for example, a job that runs during an off-peak solar window).
The battery level must stay strictly greater than 0 at every moment: before the first job and after each job. Return the smallest integer starting level that lets the whole queue finish.
def min_start_battery(usage: list[int]) -> int: ...
Constraints
0 <= len(usage) <= 10^5-10^9 <= usage[i] <= 10^9- The answer can exceed 32 bits.
Example 1
usage = [4, 2, 7]
output = 14
Starting at 14, the levels are 10, 8, 1. Starting at 13 the last job leaves 0, which is not allowed.
Example 2
usage = [5, -3, 4, -6, 1]
output = 7
Starting at 7, the levels are 2, 5, 1, 7, 6. The lowest point comes after the third job, not at the end.
Part 2. The system also has one shield that can absorb up to shield units of a single job's drain. Return the smallest starting level when the shield is used as well as possible.
Clarifying questions
- For an empty queue, is the answer
1, since the level must be positive before any job? - Must the level be strictly positive after every job, including the last?
- In Part 2, can the shield absorb part of a job's drain, and does it do anything on a recharging job?
- Is
shieldnon-negative, and can it exceed every single drain?
What a strong answer covers
- Tracks the running total of
-usage; the start must exceed the negation of the lowest prefix, so the answer ismax(1, 1 - min_prefix)withmin_prefixincluding the empty prefix0. One pass,O(n), with 64-bit or arbitrary-size integers. - Explains why the lowest point can sit in the middle (example 2), not at the end.
- Part 2: shielding job
jreduces its drain bymin(shield, usage[j]), which raises every prefix fromjonward. Evaluates eachjwith a prefix minimum beforejand a suffix minimum fromj, stillO(n). - Notes that the best job to shield is not always the largest drain: shielding a job after the lowest point does not help.
- Tests all-recharging queues, a single huge drain, and a shield larger than any drain.
Follow-ups
- Allow the shield to be split across several jobs, up to
shieldunits in total. - The jobs may run in any order: what order minimises the starting level?
- Answer many queries with different
shieldvalues quickly.
Where it's asked
What it tests
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
