Continue learning
Practice related DSA questions in the same topic.
Return the shortest contiguous length whose positive values sum to at least the positive target; return zero if impossible.
Return the shortest contiguous length whose positive values sum to at least the positive target; return zero if impossible.
def solve(values, target): left = 0 right = 0 total = 0 best = (len(values) + 1) while (right < len(values)): total = (total + values[right]) while (total >= target): best = min(best, ((right - left) + 1)) total = (total - values[left]) left = (left + 1) right = (right + 1) if (best > len(values)): return 0 return bestExpand the window at 0.
Expand the window at 0.
Buy as few adjacent food parcels as possible while reaching a calorie goal.
Expand until a window qualifies, then shrink repeatedly to locate the shortest qualifying suffix.
O(n) time · O(1) auxiliary space
Worked example · {"values":[2,3,1,2,4,3],"target":7} ⇒ 2
Edge case 1 · {"values":[],"target":3} ⇒ 0
Edge case 2 · {"values":[1,2],"target":7} ⇒ 0
Negative values would invalidate the monotonic shrinking argument.
Why does the inner loop still permit linear total work?