Quick actions

cmd+k|ctrl+k

Navigation

Languages

Sliding Window (brute force)

Snippet info

Language

Python

Visibility

public

Author

arthurpc02

Created

2026-02-22T20:47:12.04449Z

Updated

2026-02-22T21:20:27.317529Z

# Find the maximum sum of a subarray of size k.

# Example:

# Input: nums = [2, 1, 5, 1, 3, 2], k = 3

# Output: 9


# source: https://blog.algomaster.io/p/15-leetcode-patterns

def calculate(nums, k):
    max_sum = 0
    # brute force: nested loops
    for i, val in enumerate(nums):
        sum=0
        # print(f"summing from {i} to {i+k}")
        for j in nums[i:i+k]:
            if (i+k-1)>len(nums):
                break
            sum+=j
            
        # print(f"sum={sum}")
            
        if sum > max_sum:
            max_sum=sum
        
    return max_sum


print("Hello World")

test_case1_array = [2, 1, 5, 1, 3, 2]
test_case1_wind_size = 3
result1 = calculate(test_case1_array, test_case1_wind_size)
print(f"result1={result1}")
assert(result1==9)


test_case2_array = [2, 1, 11, 5, 1, 3, -12, 18, 8]
# 19, 18, 20, -3, 10, 17
test_case2_wind_size = 4
result2 = calculate(test_case2_array, test_case2_wind_size)
print(f"result1={result2}")
assert(result2==20)


print("Good-Bye CruelWorld")
INFO