Maximum Enemies Defeated Within Energy Budget
Problem
You are given two arrays of length n: layers, where layers[i] is the energy needed to defeat enemy i, and energy, where energy[i] is the minimum energy that must remain after defeating enemy i. Starting from each index i with an initial budget K, determine the maximum number of consecutive enemies (moving forward) that can be defeated without the remaining energy dropping below the required minimum after any fight.
Input / Output
- Input: arrays
layersandenergyof length n, and the initial budget K. - Output: an array of n integers — for each starting index, the count of consecutive enemies defeated.
Constraints
- 1 <= n <= 10^5, so the naive per-start simulation at O(n^2) is too slow in the worst case.
- Energy is spent and never regained; the budget resets to K for each independent starting index.
- Prefix sums of
layerscan exceed 32 bits — use 64-bit accumulators.
Example
- n=3, K=10, layers=[5,8,1], energy=[5,2,1] (1-indexed). Starting at 1: 10-5=5 >= 5 ok, then the next enemy needs 8 but only 5 remains → stop, so 1 enemy. Starting at 2: 10-8=2 >= 2 ok, then 2-1=1 >= 1 ok → 2 enemies. Starting at 3: 10-1=9 >= 1 ok → 1 enemy. Output = [1,2,1].
- Note starting at 2 beats starting at 1 despite enemy 2 being the most expensive — a greedy "start where it is cheapest" heuristic is wrong.
asked …