1.1 Maximum Sum Subarray of Size K (easy)
Problem Statement
Input: [2, 1, 5, 1, 3, 2], k=3
Output: 9
Explanation: Subarray with maximum sum is [5, 1, 3].Input: [2, 3, 4, 1, 5], k=2
Output: 7
Explanation: Subarray with maximum sum is [3, 4].public int maxSumOfContiguousSubArray(int arr[], int k) {
int maxSum = 0; // It will keep the maximum Sum of the subarrays
// with the size 'k' and it will have the result by the end of the for-loop
int windowSum = 0; // It will keep the sum of elements of that
// window till the current element
int windowStart = 0; // Starting index of the window
for(int windowEnd = 0; windowEnd < arr.length; windowEnd++) {
// For each iteration ending of the window would be increase by 1.
windowSum += arr[windowEnd]; //same as windowSum = windowSum + arr[windowEnd],
// element to the right is added to the window so value of that element added
// with the previous elements within the window
if(windowEnd >= k - 1) {
// when the window size becomes equal to k(before that the size would less that k)
maxSum = Math.max(maxSum, windowSum);
// Taking the maximum value out of maxSum and the current window(i.e windowSum)
windowSum -= arr[windowStart];
// Removing the element from the left, windowStart is the starting index of the window;
windowStart++;
// windowStart is updated by 1 as the window slides to the right
}
}
return maxSum;
}Time Complexity
Space Complexity
Last updated