Skip to content

ADDED SLIDING WINDOW ALGORITHM TO CALCULATE MAX SUM OF SUBARRAY OF SI… #12022

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions data_structures/arrays/sliding_window.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
def max_sum_subarray(arr, k):

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As there is no test file in this pull request nor any test function or class in the file data_structures/arrays/sliding_window.py, please provide doctest for the function max_sum_subarray

Please provide return type hint for the function: max_sum_subarray. If the function does not return a value, please provide the type hint as: def function() -> None:

Please provide type hint for the parameter: arr

Please provide descriptive name for the parameter: k

Please provide type hint for the parameter: k

# Edge case: if the window size is greater than the array length
if len(arr) < k:
return None

# Compute the sum of the first window
window_sum = sum(arr[:k])
max_sum = window_sum

# Slide the window from left to right
for i in range(k, len(arr)):
# Subtract the element going out of the window and add the new element coming into the window

Check failure on line 12 in data_structures/arrays/sliding_window.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

data_structures/arrays/sliding_window.py:12:89: E501 Line too long (101 > 88)
window_sum += arr[i] - arr[i - k]
max_sum = max(max_sum, window_sum)

return max_sum


# Example usage:

# Example 1: Larger array
arr1 = [4, 3, 10, 2, 8, 6, 7, 1, 9]
k1 = 4
print(
"Example 1: Maximum sum of subarray of length", k1, "is", max_sum_subarray(arr1, k1)
)

# Example 2: All elements are negative
arr2 = [-2, -3, -1, -5, -6]
k2 = 2
print(
"Example 2: Maximum sum of subarray of length", k2, "is", max_sum_subarray(arr2, k2)
)

# Example 3: Array with all elements equal
arr3 = [5, 5, 5, 5, 5, 5]
k3 = 3
print(
"Example 3: Maximum sum of subarray of length", k3, "is", max_sum_subarray(arr3, k3)
)

# Example 4: Small array
arr4 = [1, 2]
k4 = 2
print(
"Example 4: Maximum sum of subarray of length", k4, "is", max_sum_subarray(arr4, k4)
)

# Example 5: k greater than the array length
arr5 = [7, 8, 9]
k5 = 5
print(
"Example 5: Maximum sum of subarray of length", k5, "is", max_sum_subarray(arr5, k5)
)
Loading