Earliest Second to Mark Indices II

You are given two 1-indexed integer arrays, nums and changeIndices, having lengths n and m, respectively.

Initially, all indices in nums are unmarked. Your task is to mark all indices in nums.

In each second, s, in order from 1 to m (inclusive), you can perform one of the following operations:

  • Choose an index i in the range [1, n] and decrement nums[i] by 1.
  • Set nums[changeIndices[s]] to any non-negative value.
  • Choose an index i in the range [1, n], where nums[i] is equal to 0, and mark index i.
  • Do nothing.

Return an integer denoting the earliest second in the range [1, m] when all indices in nums can be marked by choosing operations optimally, or -1 if it is impossible.

Example 1
Inputnums = [3,2,3], changeIndices = [1,3,2,2,2,2,3]
Output6
By setting the first three referenced indices to 0 and then marking indices 1, 2, and 3, all indices can be marked by second 6 and not earlier.
Example 2
Inputnums = [0,0,1,2], changeIndices = [1,2,1,2,1,2,1,2]
Output7
An optimal sequence marks indices 1 and 2, decrements indices 4 and 3 to 0, and marks the remaining indices by second 7, which is the earliest possible second.

Constraints

  • 1 <= n == nums.length <= 5000
  • 0 <= nums[i] <= 10^9
  • 1 <= m == changeIndices.length <= 5000
  • 1 <= changeIndices[i] <= n

Asked at 2 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate