Continue learning
Practice related DSA questions in the same topic.
Among all consecutive windows containing exactly target items, return the largest sum.
Among all consecutive windows containing exactly target items, return the largest sum.
def solve(values, target): total = 0 right = 0 while (right < target): total = (total + values[right]) right = (right + 1) best = total left = 0 while (right < len(values)): total = ((total - values[left]) + values[right]) best = max(best, total) left = (left + 1) right = (right + 1) return bestBuild the first window.
Build the first window.
A camera frame pans across a row; only the two edges change.
When moving one place, remove the outgoing value and add the incoming one.
O(n) time · O(1) auxiliary space
Worked example · {"values":[4,-1,3,5,-2],"target":2} ⇒ 8
Edge case 1 · {"values":[-5,-2],"target":1} ⇒ -2
Edge case 2 · {"values":[2],"target":1} ⇒ 2
A best sum of zero fails when every valid window has negative sum.
Could the same update maintain a window minimum?