Let’s discuss a interesting problem maximum sum subarray of size k
Given an array of positive integers and a positive number K. Write a code to find the maximum sum subarray of size k.
For example:
1 2 3 4 5 |
Example 1: Input: {2, 1, 5, 1, 3, 2}, K = 3 Output: 9 { 5, 1, 3} |
Let’s first understand what all subarrays we can form whose size is 3.
i) First subarray is {2, 1, 5} and it’s sum is 8.
ii) Second subarray is {1, 5, 1} and it’s sum is 7.
iii) Third subarray is {5, 1,3} and it’s sum is 9.
iv) Fourth subarray is {1, 3, 2} and it’s sum is 6.
Out of all these subarrays of size three, the maximum sum subarray is {5, 1, 3} and it’s sum is 9.