← 返回 capitalone 的题目列表Repeated Leading-Nonzero Subtraction
类型:qbank
Repeatedly: find the leftmost non-zero entry `x` in the array, subtract `x` from each subsequent entry that is `≥ x`, stop at the first entry strictly less than `x`, then add `x` to a running answer. Return the final answer when the array is all zeros.
Requirements
Input: a non-negative integer array nums.
Pseudocode:
If all entries are 0, return the accumulated answer.
Find the leftmost index k where nums[k] > 0; let x = nums[k].
For each j > k: if nums[j] >= x then nums[j] -= x; otherwise stop the inner pass (do not modify nums[j]).
Add x to the answer.
Set nums[k] = 0 and repeat.
Note: the leading entry itself becomes 0 (it is conceptually subtracted in step 4), and the inner pass halts at the first element strictly less than x.
Examples
nums = [3, 5, 5, 1]
ans = 0
Iteration 1: x = 3, nums -> [0, 2, 2, 1], ans = 3
Iteration 2: x = 2, nums -> [0, 0, 0, 1], ans = 5
Iteration 3: x = 1, nums -> [0, 0, 0, 0], ans = 6
Return 6
Notes
The leftmost non-zero index only moves right (everything before it is already zero), so the process runs at most n iterations with an O(n) inner pass each — O(n²) worst case for the direct simulation. At the OA's input sizes that is borderline: careless implementations that re-scan and re-copy the array every iteration are the ones that time out on the hidden tests.
Beware of shortcut formulas: decomposing the array into monotone non-decreasing runs and summing per-run contributions does not work — an early small leader subtracts across later run boundaries (try [1, 3, 2, 4]: the simulation yields 6, while a per-run decomposition gives 7). Trust the simulation.
The simpler safe approach for the OA is the direct simulation but with an early-exit when the inner pass finds the boundary: that prunes enough work to pass the standard hidden-test set as long as you avoid re-scanning from index 0 each iteration. Track the current k and resume from k+1 rather than restarting.
Edge cases: array already all zeros (return 0); array with a single non-zero entry; descending array such as [5, 4, 3, 2, 1] where every iteration only processes the leading element.
Preparation
Write the direct simulation first with the resume-from-k+1 optimisation; verify the worked example by hand.
Drill the boundary behaviour on paper: an iteration's inner pass stops at the first element strictly below x, and that element later becomes a leader at its reduced value. Seeing this interaction is what stops you from reaching for an (incorrect) run-based shortcut.
Hand-trace [3, 5, 5, 1, 7, 7] step by step; off-by-one between "inner pass stops at" and "next iteration starts from" is the common bug.