Answers for "sliding window maximum sum subarray"

C++
0

sliding window maximum sum subarray

#include <bits/stdc++.h>

using namespace std;

int main()
{
    int n;
    cout<<"enter the size of the array:"<<endl;
    cin>>n;
    int arr[n];
    cout<<"Enter the elements of the array:"<<endl;
    for(int i=0;i<n;i++)
    {
        cin>>arr[i];
    }
    int k;
    cout<<"Enter the size of the sub array"<<endl;
    cin>>k;
    int i=0;
    int j=0;
    int max_sum=0;
    int sum=0;
    while(j<n)
    {
        sum=sum+arr[j];
        if(j-i+1<k)
        {
            j++;
        }
        else if(j-i+1==k)
        {
            max_sum=max(sum,max_sum);
            sum=sum-arr[i];
            i++;
            j++;
        }
    }
    cout<<max_sum<<endl;

    return 0;
}
Posted by: Guest on June-20-2021

Browse Popular Code Answers by Language