sliding window maximum sum subarray

Solutions on MaxInterview for sliding window maximum sum subarray by the best coders in the world

showing results for - "sliding window maximum sum subarray"
Jaylon
28 Feb 2016
1#include <bits/stdc++.h>
2
3using namespace std;
4
5int main()
6{
7    int n;
8    cout<<"enter the size of the array:"<<endl;
9    cin>>n;
10    int arr[n];
11    cout<<"Enter the elements of the array:"<<endl;
12    for(int i=0;i<n;i++)
13    {
14        cin>>arr[i];
15    }
16    int k;
17    cout<<"Enter the size of the sub array"<<endl;
18    cin>>k;
19    int i=0;
20    int j=0;
21    int max_sum=0;
22    int sum=0;
23    while(j<n)
24    {
25        sum=sum+arr[j];
26        if(j-i+1<k)
27        {
28            j++;
29        }
30        else if(j-i+1==k)
31        {
32            max_sum=max(sum,max_sum);
33            sum=sum-arr[i];
34            i++;
35            j++;
36        }
37    }
38    cout<<max_sum<<endl;
39
40    return 0;
41}
42