Find the maximum sum of a contiguous subarray of length k

Quick Overview

Given an integer array that may hold negative values, return the largest sum of any contiguous subarray of exactly k elements. The problem tests the fixed-size sliding window pattern, constant-time updates of a running sum, and correct handling of all-negative input.

Find the maximum sum of a contiguous subarray of length k

Company: Hugging Face

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

Given an integer array `nums` and an integer `k`, find the **maximum sum** of any contiguous subarray of length exactly `k`. Return the maximum sum obtained by sliding a window of size `k` across the array from left to right. ### Function Signature ```python def max_window_sum(nums: list[int], k: int) -> int: ``` ### Constraints - `1 <= nums.length <= 10^5` - `-10^4 <= nums[i] <= 10^4` - `1 <= k <= nums.length` ### Examples ```text Input: nums = [2,1,5,1,3,2], k = 3 Output: 9 ``` The windows of length 3 sum to 8, 7, 9 and 6. The subarray [5, 1, 3] gives the maximum, 9. ```text Input: nums = [-1,-2,-3,-4,-5], k = 2 Output: -3 ``` All values are negative. The window sums are -3, -5, -7 and -9, so [-1, -2] gives the maximum, -3. ```text Input: nums = [4,-1,2], k = 3 Output: 5 ``` When `k` equals the array length there is a single window, the whole array, and its sum is 4 + (-1) + 2 = 5.

Overview: Given an integer array that may hold negative values, return the largest sum of any contiguous subarray of exactly k elements. The problem tests the fixed-size sliding window pattern, constant-time updates of a running sum, and correct handling of all-negative input.

Hugging Face logo
Hugging Face
Nov 24, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

Given an integer array nums and an integer k, find the maximum sum of any contiguous subarray of length exactly k.

Return the maximum sum obtained by sliding a window of size k across the array from left to right.

Function Signature

def max_window_sum(nums: list[int], k: int) -> int:

Constraints

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • 1 <= k <= nums.length

Examples

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

The windows of length 3 sum to 8, 7, 9 and 6. The subarray [5, 1, 3] gives the maximum, 9.

Input: nums = [-1,-2,-3,-4,-5], k = 2
Output: -3

All values are negative. The window sums are -3, -5, -7 and -9, so [-1, -2] gives the maximum, -3.

Input: nums = [4,-1,2], k = 3
Output: 5

When k equals the array length there is a single window, the whole array, and its sum is 4 + (-1) + 2 = 5.