Given an array 'arr' and a number 'k'.
Find the largest sum of the subarray containing at least 'k' numbers. It may be assumed that the size of the array is at least 'k'.
Input: 'arr' = [1, 4, -2] and 'k' = 2
Output: 5
Explanation: The subarray with the largest sum is [1, 4]. So the sum will be 5.
The first line contains two space-separated integers, ‘n’ and ‘k’.
The second line contains ‘n’ space-separated integers, representing the array ‘arr’ elements.
Print the largest sum of the subarray containing at least 'k' numbers.
You do not need to print anything. It has already been taken care of. Just implement the given function.
4 2
-3 -1 2 -2
1
The subarray with the largest sum is [-1, 2]. So the sum will be 1.
3 2
1 4 -2
5
The subarray with the largest sum is [1, 4]. So the sum will be 5.
4 4
-14 12 11 -20
-11
The expected time complexity is O('n').
1 <= 'n' <= 10 ^ 5
1 <= 'k' <= 'n'
-10 ^ 5 <= 'arr[i]' <= 10 ^ 5
Time Limit: 1 sec
Try to check all subarrays.
The basic idea is to check all the subarrays possible for the array. We find the sum of all subarrays having at least ‘k’ numbers and find the maximum sum from all of them.
Here is the algorithm :
O(n ^ 2), where ‘n’ is the size of the array.
We iterate the array once to iterate the elements and run another nested loop to find the subarrays. Therefore, the overall time complexity will be O(n ^ 2).
O(1)
We don’t use any extra space. Therefore, the overall space complexity will be O(1).