← Questions

Levels cleared from every starting point

0
UberCoding

A coding interview question asked at Uber. It tests prefix sums, two pointers and arrays.

A game has n levels in a row. You are given two integer arrays of length n, layers and energy, and an integer K.

A run that starts at level i begins with exactly K energy and plays levels i, i+1, i+2, ... in order. At level j:

  1. Pay layers[j] energy.
  2. If the energy you have left is at least energy[j], you clear the level, score 1 point, and move on to j+1.
  3. Otherwise the run ends at once. No later level counts.

Every run is independent and starts again with K energy.

Return an array answer of length n where answer[i] is the score of the run that starts at level i.

Implement:

def max_levels(layers: list[int], energy: list[int], k: int) -> list[int]: ...

Constraints

  • 1 <= n <= 10^5
  • 0 <= layers[j], energy[j] <= 10^9
  • 0 <= K <= 10^14

Example 1

layers = [2, 3, 1, 4], energy = [5, 2, 4, 1], K = 10
output = [3, 3, 2, 1]

From level 0: 10-2=8 (>=5, pass), 8-3=5 (>=2, pass), 5-1=4 (>=4, pass), 4-4=0 (<1, stop). Score 3.
From level 1: 7 (>=2), 6 (>=4), 2 (>=1). Score 3.

Example 2

layers = [0, 0], energy = [10, 0], K = 5
output = [0, 1]

Level 0 needs 10 energy left, so a run from 0 scores nothing. A run from 1 clears level 1.

An O(n^2) simulation is a fine start. Aim for O(n) or O(n log n).

Clarifying questions

  • Is the check on the energy after paying, as written, so energy can go below zero and then fail?
  • Is the run over once one level fails, even if later levels are free?
  • Can K be 0?
  • Will there be many runs with different K values?

What a strong answer covers

  • Uses prefix sums of layers. Level j passes in a run from i when prefix[j + 1] + energy[j] <= K + prefix[i].
  • Notes that the right side never decreases as i grows (layers are non-negative). So the first failing level never moves left.
  • Uses two pointers for O(n) time, or binary search over a sparse table or segment tree for O(n log n).
  • Uses 64-bit values (K goes up to 10^14) and caps each answer at n - i.
  • Tests both examples, all zeros, a first level that always fails, and a run that clears to the end.

Follow-ups

  • A different K for each starting level.
  • One level may be skipped per run.
  • Clearing a level gives back some energy, so the threshold is no longer monotone.
  • Return the start with the best score.

Where it's asked

What it tests

prefix sums · two pointers · arrays

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