TheAlgorithms/Python · error · ValueError
Invalid Input
Error message
Invalid Input
What it means
Raised by max_sum_in_array() in maths/max_sum_sliding_window.py when len(array) < k or k < 0. The sliding-window algorithm needs at least one full window of size k inside the array, so a window larger than the array (or a negative size) makes the problem undefined and the function raises ValueError('Invalid Input').
Source
Thrown at maths/max_sum_sliding_window.py:31
def max_sum_in_array(array: list[int], k: int) -> int:
"""
Returns the maximum sum of k consecutive elements
>>> arr = [1, 4, 2, 10, 2, 3, 1, 0, 20]
>>> k = 4
>>> max_sum_in_array(arr, k)
24
>>> k = 10
>>> max_sum_in_array(arr,k)
Traceback (most recent call last):
...
ValueError: Invalid Input
>>> arr = [1, 4, 2, 10, 2, 13, 1, 0, 2]
>>> k = 4
>>> max_sum_in_array(arr, k)
27
"""
if len(array) < k or k < 0:
raise ValueError("Invalid Input")
max_sum = current_sum = sum(array[:k])
for i in range(len(array) - k):
current_sum = current_sum - array[i] + array[i + k]
max_sum = max(max_sum, current_sum)
return max_sum
if __name__ == "__main__":
from doctest import testmod
from random import randint
testmod()
array = [randint(-1000, 1000) for i in range(100)]
k = randint(0, 110)
print(
f"The maximum sum of {k} consecutive elements is {max_sum_in_array(array, k)}"
)
View on GitHub (pinned to f5988cc097)
Solutions
- Choose k <= len(array), typically k in [1, len(array)].
- Clamp derived window sizes: k = max(1, min(k, len(array))).
- Validate k against array length at the point where k is configured, not deep in the call stack.
Example fix
# before max_sum_in_array([2, 1, 5, 1, 3, 2], 10) # window larger than array # after k = min(10, len(arr)) max_sum_in_array(arr, k)
Defensive patterns
Strategy: validation
Validate before calling
if not 1 <= k <= len(array):
k = max(1, min(k, len(array))) # or raise with your own message Prevention
- Validate window size against data length where k is configured.
- Prefer computing k as a fraction of len(array) with clamping.
When it happens
Trigger: max_sum_in_array(arr, 10) where arr has 9 or fewer elements (e.g. the doctest case arr=[2,1,5,1,3,2], k=10), or any negative k such as max_sum_in_array(arr, -1).
Common situations: k computed from user input or from len(array) arithmetic (e.g. k = len(arr) + margin), small test fixtures with a hardcoded window size, or off-by-one errors when deriving k.
Related errors
- surface_area_cube() only accepts non-negative values
- surface_area_cuboid() only accepts non-negative values
- surface_area_sphere() only accepts non-negative values
- surface_area_hemisphere() only accepts non-negative values
- surface_area_cone() only accepts non-negative values
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/0c6925fc55205e7c.
Report an issue: GitHub.