Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.

Try one problem
0
Problem

Max Sum Subarray of Size K

LeetCode #643Easy
Find the K-length contiguous subarray with the largest sum

Given an integer array and a window size k, find the maximum sum among all contiguous subarrays of length k.

step 1 / 37
2
1
5
1
3
2
[0][1][2][3][4][5]
Brute force · recompute each window
1given arr, K
2max_sum ← −∞
3for i ← 0 to n − K:
4 sum ← 0
5 for j ← i to i + K − 1:
6 sum += arr[j]
7 max_sum = max(max_sum, sum)
8return max_sum
state
  • n6
  • K3

line 1Find the maximum sum of any contiguous subarray of size K = 3.