Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Sliding Window Max Subarray Sum

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Sliding Window Max Subarray Sum. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Spotify analyzes contiguous windows of playlist metrics, such as track engagement scores. Given an integer array nums and a window size k, return the maximum sum among all contiguous subarrays containing exactly k elements.

Formal Specification

Implement max_subarray_sum(nums, k).

  • Input: nums, a non-empty list of integers, and k, an integer window size.
  • Output: An integer representing the largest sum of any contiguous subarray of length exactly k.
  • The order of elements must remain unchanged, and every candidate window must contain exactly k elements.

Use a fixed-size sliding window rather than recomputing every window from scratch.

Constraints

  • 1 <= k <= len(nums) <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • The result fits in a signed 64-bit integer

Function Signature

def max_subarray_sum(nums, k):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output