A fixed-width sliding total updates an adjacent interval by adding its entering value and subtracting its departing value.
Python window exercise: verify a fixed-width maximum against direct slices
Operation contract
The receipt exercise returns the largest sum over exactly k adjacent amounts. It rejects an empty batch, boolean values and a width outside one through the batch length. Negative amounts are accepted, so the best total must start from the first actual window rather than an invented zero. The independent answer uses direct slices on the same small fixture.
Failure and ownership boundary
The operation returns a total without the window’s identity or tie position. Those would require another declared return contract. Its input list remains unchanged. Python sliding window: longest span without repeated symbols and Hypothesis property tests: compare generated cases with an independent contract extend the exercise to varied sequences without copying the rolling update into the oracle.
Working program
def maximum_window(amounts, width):
if not 1 <= len(amounts) <= 128 or any(type(amount) is not int for amount in amounts):
raise ValueError("bounded integer batch required")
if type(width) is not int or not 1 <= width <= len(amounts):
raise ValueError("window width rejected")
running = sum(amounts[:width]); best = running
for index in range(width, len(amounts)):
running += amounts[index] - amounts[index - width]
best = max(best, running)
return best
amounts = [125, -50, 250, 75]
print(maximum_window(amounts, 2))
print("direct answer:", max(sum(amounts[index:index + 2]) for index in range(len(amounts) - 1)))
print("negative answer:", maximum_window([-5, -3], 1))
try:
maximum_window(amounts, 0)
except ValueError:
print("zero width rejected")Output
325
direct answer: 325
negative answer: -3
zero width rejectedCosts and limits
The scan performs O(n) arithmetic operations. Its initial slice retains O(k) temporary references in this implementation, followed by O(1) rolling state. The direct-slice oracle costs O(nk), which is acceptable for bounded tests rather than the main algorithm.
Common Mistakes
- Initialize from an actual window when all amounts can be negative.
- An oracle should compute the answer independently of the rolling update.
Connected lessons
Python sliding window: longest span without repeated symbols, Hypothesis property tests: compare generated cases with an independent contract, Python segment tree: point replacement and half-open range sums.
