Skip to main content

Minimum Data Center Battery Capacity

easy
Software engineer

A data center needs to process a queue of computational tasks sequentially. The energy consumption for these tasks is strictly defined. The rules for the processing sequence are as follows:

  • The system consumes usage[i] units of energy to complete task i.
  • The system's battery level must remain strictly greater than 0 at all times to prevent a shutdown.
  • The system is equipped with a single smart backup generator. You can choose to activate this generator for exactly one task.
  • When activated for a task, the generator reduces the cost of that task by min(usage[i], maxRecovery).

Determine the minimum starting battery capacity required to complete all tasks without the system ever reaching a battery level of 0 or less.

Example 1

Input

usage = [1, 2, 3], maxRecovery = 4

Output

4

Explanation

To minimize the starting capacity, we should use the backup generator on the task where it provides the maximum benefit. In this case, task 3 (usage 3) is less than maxRecovery (4), so the generator covers the full 3 units.
1. Start with 4 units.
2. Task 1 (1): 4 - 1 = 3 units left.
3. Task 2 (2): 3 - 2 = 1 unit left.
4. Task 3 (3): Generator covers min(3, 4) = 3. 1 - 0 = 1 unit left.
The battery stayed > 0 at all steps. If we used the generator on Task 2, we would have needed a starting capacity of 5.

Example 2

Input

usage = [1, 2, 3], maxRecovery = 1

Output

6

Explanation

The maximum reduction we can get on any task is 1. The total energy needed without the generator is 1 + 2 + 3 = 6. With the generator, total energy is 5. To keep battery > 0 at the end, we need 5 + 1 = 6.

Example 3

Input

usage = [5, 5, 5], maxRecovery = 5

Output

11

Explanation

One task is completely mitigated by the generator. Total cost effectively becomes 5 + 5 + 0 = 10. Minimum battery to stay above zero is 11.

Constraints

  • 1 <= usage.length <= 10⁵
  • 1 <= maxRecovery <= 10⁹
  • 1 <= usage[i] <= 10⁹

OA

ArrayGreedySimulation
Language
Code editor loads in the browser.

Output

Input

[1,2,3]
4

Expected

4

Your output

Run to see your output.