Frontend School

Maximum Sum of a Fixed-Length Subarray

DSA
easy

Maximum Sum of a Fixed-Length Subarray

Easy
Arrays
Sliding Window

Overview

In many data analysis scenarios, it's crucial to identify trends or peak values within a continuous stream of data over a specific duration. For instance, monitoring sensor readings, financial data, or network traffic often involves analyzing fixed-size segments to detect anomalies or maximum activity periods. This problem asks you to find the highest sum achievable from any contiguous subarray of a predefined length within a given array of integers.

What you need to do / Task

Given an array of integers nums and an integer k, your task is to find the maximum sum of any subarray (contiguous block of elements) of length k.

Input & output

  • Input:
    • nums: An array of integers (number[]). Represents the data stream or sequence.
    • k: An integer (number). Represents the fixed length of the subarray we are interested in.
  • Output:
    • A single integer (number) representing the maximum sum found among all subarrays of length k.

Clarifications

  • Negative numbers: The nums array can contain negative integers. The sum should correctly account for them.
  • Array size vs. k: You can assume k will always be less than or equal to the length of nums.

Examples

1

Example 1

Input:

nums = [1,2,3,4,5], k = 3

Output:

12

Note:

Subarrays of length 3 are: [1,2,3] sum = 6; [2,3,4] sum = 9; [3,4,5] sum = 12. The maximum sum is 12.

2

Example 2

Input:

nums = [1,5,2,8,1,9], k = 2

Output:

17

Note:

Subarrays of length 2: [1,5] sum=6; [5,2] sum=7; [2,8] sum=10; [8,1] sum=9; [1,9] sum=10. The maximum sum is 17 (from [8,9]).

3

Example 3

Input:

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

Output:

-3

Note:

Subarrays of length 2: [-1,-2] sum=-3; [-2,-3] sum=-5; [-3,-4] sum=-7; [-4,-5] sum=-9. The maximum sum is -3.

Constraints

Constraints & assumptions

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

What interviewers evaluate

  • Algorithmic correctness: Does the solution correctly identify the maximum sum for all valid subarrays of length k?
  • Efficiency: Is the solution optimal in terms of time and space complexity?
  • Code quality: Is the code clean, readable, and well-structured, demonstrating good software engineering practices?
  • Edge case handling: Does the solution correctly handle edge cases such as k=1 or when the array nums has exactly k elements?

Loading editor...