Ctrl K

Fewest Rounds to Zero

Medium
You get an array of non-negative integers levels and a list of rounds rounds, where rounds[j] = [l, r, val]. During a round, every cell from index l to r inclusive may be lowered by any whole amount from 0 to val, chosen separately for each cell. Rounds are applied strictly in order. Find the smallest k ≥ 0 such that after the first k rounds the array can be made all zeros. If even all the rounds are not enough, return -1.
Example 1
levels=[3, 1, 2], rounds=[[0, 1, 2], [2, 2, 1], [0, 2, 1], [1, 2, 4]] → 3

After two rounds the cells can drop by at most [2, 2, 1], while cell 0 needs 3 and cell 2 needs 2. After the third round the budget [3, 3, 2] covers everything, so the answer is 3.

Example 2
levels=[0, 0], rounds=[[0, 1, 1]] → 0

The array is already all zeros, so no rounds are needed.

Example 3
levels=[5], rounds=[[0, 0, 2], [0, 0, 2]] → -1

Even both rounds together lower the cell by at most 4, which is not enough.

Constraints
  • 1 ≤ len(levels) ≤ 10⁵
  • 0 ≤ levels[i] ≤ 5·10⁵
  • 1 ≤ len(rounds) ≤ 10⁵
  • rounds[j] = [l, r, val], 0 ≤ l ≤ r < len(levels)
  • 1 ≤ val ≤ 5
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsShortest Stretch to the Goal MediumWindows With a Small Product MediumLongest Run of Ones With k Fixes MediumLargest Light Square MediumTrim the Ends to a Target Medium
loading Python…
Input
levels=[3, 1, 2], rounds=[[0, 1, 2], [2, 2, 1], [0, 2, 1], [1, 2, 4]]
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 69 tests on the server, hidden ones included.