← Questions

Minimum starting battery for a task queue

0
AmazonCoding

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 shield non-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 is max(1, 1 - min_prefix) with min_prefix including the empty prefix 0. 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 j reduces its drain by min(shield, usage[j]), which raises every prefix from j onward. Evaluates each j with a prefix minimum before j and a suffix minimum from j, still O(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 shield units in total.
  • The jobs may run in any order: what order minimises the starting level?
  • Answer many queries with different shield values quickly.

Where it's asked

What it tests

prefix sums · arrays · greedy

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