0% found this document useful (0 votes)
57 views6 pages

Maximum Sum Subarray of Size K (Easy)

This document describes the problem of finding the maximum sum subarray of size K in an array of positive numbers. It provides an example, asks the reader to try solving it, and then presents two solutions. The first solution uses a brute force approach with time complexity of O(N*K). The second solution improves this to O(N) time by using a sliding window approach that avoids recomputing sums by subtracting the outgoing and adding the incoming elements at each step. It also analyzes the time and space complexities of the improved algorithm.

Uploaded by

NITHISHKUMAR.S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views6 pages

Maximum Sum Subarray of Size K (Easy)

This document describes the problem of finding the maximum sum subarray of size K in an array of positive numbers. It provides an example, asks the reader to try solving it, and then presents two solutions. The first solution uses a brute force approach with time complexity of O(N*K). The second solution improves this to O(N) time by using a sliding window approach that avoids recomputing sums by subtracting the outgoing and adding the incoming elements at each step. It also analyzes the time and space complexities of the improved algorithm.

Uploaded by

NITHISHKUMAR.S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Maximum Sum Subarray of Size K (easy)

We'll cover the following

• Problem Statement
• Try it yourself
• Solution
• Code
• A better approach
• Time Complexity
• Space Complexity

Problem Statement
Given an array of positive numbers and a positive number ‘k,’ find the maximum sum of any contiguous subarray of size ‘k’.

Example 1:

Input: [2, 1, 5, 1, 3, 2], k=3


Output: 9
Explanation: Subarray with maximum sum is [5, 1, 3].
Example 2:

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


Output: 7
Explanation: Subarray with maximum sum is [3, 4].

Try it yourself
Try solving this question here:

Java Python3 JS C++

class MaxSumSubArrayOfSizeK {
public static int findMaxSumSubArray(int k, int[] arr) {
// TODO: Write your code here
return -1;
}
}

Test Save Reset

Solution
A basic brute force solution will be to calculate the sum of all ‘k’ sized subarrays of the given array to find the subarray with the
highest sum. We can start from every index of the given array and add the next ‘k’ elements to find the subarray’s sum. Following
is the visual representation of this algorithm for Example-1:
K=3

Window Sum = 0
2 1 5 1 3 2
Max Sum = 0

Window Sum = 8 2 1 5 1 3 2
Max Sum = 8

Window Sum = 7
2 1 5 1 3 2
Max Sum = 8

Window Sum = 9
Max Sum = 9 2 1 5 1 3 2

Window Sum = 6
2 1 5 1 3 2
Max Sum = 9

Code
Here is what our algorithm will look like:

Java Python3 C++ JS

class MaxSumSubArrayOfSizeK {
public static int findMaxSumSubArray(int k, int[] arr) {
int maxSum = 0, windowSum;
for (int i = 0; i <= arr.length - k; i++) {
windowSum = 0;
for (int j = i; j < i + k; j++) {
windowSum += arr[j];
}
maxSum = Math.max(maxSum, windowSum);
}

return maxSum;
}

public static void main(String[] args) {


System.out.println("Maximum sum of a subarray of size K: "
+ MaxSumSubArrayOfSizeK.findMaxSumSubArray(3, new int[] { 2, 1, 5, 1, 3, 2 }));
System.out.println("Maximum sum of a subarray of size K: "
+ MaxSumSubArrayOfSizeK.findMaxSumSubArray(2, new int[] { 2, 3, 4, 1, 5 }));
}
}

Run Save Reset

The above algorithm’s time complexity will be O(N ∗ K), where ‘N’ is the total number of elements in the given array. Is it
possible to find a better algorithm than this?

A better approach
If you observe closely, you will realize that to calculate the sum of a contiguous subarray, we can utilize the sum of the previous
subarray. For this, consider each subarray as a Sliding Window of size ‘k.’ To calculate the sum of the next subarray, we need to
slide the window ahead by one element. So to slide the window forward and calculate the sum of the new position of the sliding
window, we need to do two things:

1. Subtract the element going out of the sliding window, i.e., subtract the first element of the window.
2. Add the new element getting included in the sliding window, i.e., the element coming right after the end of the window.
This approach will save us from re-calculating the sum of the overlapping part of the sliding window. Here is what our algorithm
will look like:

Java Python3 C++ JS

class MaxSumSubArrayOfSizeK {
public static int findMaxSumSubArray(int k, int[] arr) {
int windowSum = 0, maxSum = 0;
int windowStart = 0;
for (int windowEnd = 0; windowEnd < arr.length; windowEnd++) {
windowSum += arr[windowEnd]; // add the next element
// slide the window, we don't need to slide if we've not hit the required window size of 'k'
if (windowEnd >= k - 1) {
maxSum = Math.max(maxSum, windowSum);
windowSum -= arr[windowStart]; // subtract the element going out
windowStart++; // slide the window ahead
}
}

return maxSum;
}

public static void main(String[] args) {


System.out.println("Maximum sum of a subarray of size K: "
+ MaxSumSubArrayOfSizeK.findMaxSumSubArray(3, new int[] { 2, 1, 5, 1, 3, 2 }));
System.out.println("Maximum sum of a subarray of size K: "
+ MaxSumSubArrayOfSizeK.findMaxSumSubArray(2, new int[] { 2, 3, 4, 1, 5 }));
}
}

Run Save Reset

Time Complexity
The time complexity of the above algorithm will be O(N ).

Space Complexity
The algorithm runs in constant space O(1).

Back Completed Next

Introduction Smallest Subarray With a Greater Sum (easy)

You might also like