Sponsored
Sponsored
Solve with full IDE support and test cases
Use these hints if you're stuck. Try solving on your own first.
Consider using binary search.
Suppose the <code>answer <= x</code>; we can mark each index as late as possible. Namely, mark each index at the last occurrence in the array <code>changeIndices[1..x]</code>.
When marking an index, which is the last occurrence at the second <code>i</code>, we check whether we have a sufficient number of decrement operations to mark all the previous indices whose last occurrences have already been marked, and the current index, i.e., <code>i - sum_of_marked_indices_values - cnt_of_marked_indices >= nums[changeIndices[i]]</code>.
The answer is the earliest second when all indices can be marked after running the binary search or <code>-1</code> if there is no such second.