1.1 Maximum Sum Subarray of Size K (easy)
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:
Example 2:
How can we solve the question?
We can think of the 'k' as window size of sliding window in an array.
With each slide we will remove an element from the left and add an element from the right.
Calculate the sum for that window and compare the sum of that window to prevous max sum of sliding windows.
Beware: Until the window size becomes equal to 'k', we have to just add the next element to the right but we shouldn't remove the element to the left.
So, code for that condition:
Time Complexity
The time complexity of the above algorithm will be O(N).
Space Complexity
The algorithm runs in constant space O(1).
Last updated