forked from Midway91/HactoberFest2023
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWindow sliding
More file actions
32 lines (26 loc) · 691 Bytes
/
Window sliding
File metadata and controls
32 lines (26 loc) · 691 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <bits/stdc++.h>
using namespace std;
// Returns maximum sum in a subarray of size k.
int maxSum(int arr[], int n, int k)
{
// Initialize result
int max_sum = INT_MIN;
// Consider all blocks starting with i.
for (int i = 0; i < n - k + 1; i++) {
int current_sum = 0;
for (int j = 0; j < k; j++)
current_sum = current_sum + arr[i + j];
// Update result if required.
max_sum = max(current_sum, max_sum);
}
return max_sum;
}
// Driver code
int main()
{
int arr[] = { 1, 4, 2, 10, 2, 3, 1, 0, 20 };
int k = 4;
int n = sizeof(arr) / sizeof(arr[0]);
cout << maxSum(arr, n, k);
return 0;
}