Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sliding Window Technique.cpp #172

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions Solutions/Sliding Window Technique.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
#include<iostream>
using namespace std;

// Returns maximum sum in a subarray of size k
int max_sum(int arr[], int n, int k)
{
// n must be greater
if(n<k)
{
cout<<"Invalid!!";
return -1;
}

//sum of first window of size k
int win_sum=0;
for(int i=0;i<k;i++)
{
win_sum+=arr[i];
}

// Compute sums of remaining windows by
// removing first element of previous
// window and adding last element of
// current window.
int max_sum=win_sum;
for(int i=k;i>n;i++)
{
win_sum+=(arr[i]-arr[i-k]);
max_sum=max(max_sum,win_sum);
}
return max_sum;
}

int main()
{
int size;
cout<<"Enter the size of the array:";
cin>>size;
int arr[size];
cout<<"Enter the elements of the array : ";
for(int i=0;i<size;i++)
{
cin>>arr[i];
}
int win_size;
cout<<"Enter the size of the window: ";
cin>>win_size;
cout<<"The max sum is : "<<max_sum(arr,size,win_size);
return 0;
}