1)Max Sum Subarray of size K- (sliding window)
Given an array of integers Arr of size N and a number K. Return the maximum sum of a subarray of size K.
Example 1:
Input:
N = 4, K = 2
Arr = [100, 200, 300, 400]
Output:
700
Explanation:
Arr3 + Arr4 =700,
which is maximum.
Example 2:
Input:
N = 4, K = 4
Arr = [100, 200, 300, 400]
Output:
1000
Explanation:
Arr1 + Arr2 + Arr3
+ Arr4 =1000,
which is maximum.
c++ implementation:
int maximumSumSubarray(int k, vector<int> &a , int n) { int i=0; int j=0; int s=0; int ms=0; while(j<n) { if(j-i+1<k) { s=s+a[j]; } else if(j-i+1==k) { s=s+a[j]; ms=s; } else { s=s-a[i]; s=s+a[j]; ms=max(s,ms); i++; } j++; } return ms; }
time complexity: O(n)
space complexity: O(1)
space complexity: O(1)
No comments