Menu
CoddyTech

Maximum Sum Subarray of Size K

You get an array of integers nums and a window length k. Look at every run of exactly k neighbouring elements and return the largest sum among them. The values can be negative, so the answer can be negative too.

Function

maxSumSubarray(nums: integer-array, k: integer) → integer
numsinteger-array
the array of integers
kinteger
how many neighbouring elements each window holds
Returnsinteger
the largest sum of any k consecutive elements

Constraints

  • 1 ≤ k ≤ nums.length ≤ 104
  • -104 ≤ nums[i] ≤ 104

Examples

Input
nums = [4, -1, 3, 7, -2, 5, 1]k = 3
Output
10
Explanation
The five windows of length 3 add up to 6, 9, 8, 10 and 4. The largest is 7 + (-2) + 5 = 10.

lock icon+15 hidden tests on Submit

challenge icon

Follow-up

Can you also return where the best window starts, picking the leftmost one when several windows tie?

Reset code
def maxSumSubarray(nums, k):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

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

Expected

10