Skip to content

Added 1 DP and 1 Greedy algorithms code in cpp #357

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
33 changes: 33 additions & 0 deletions algorithms/dynamic-programming/Sliding Windows.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
////////////////////////////////////////////////////////////////////
///////////////WINDOW SLIDING TECHNIQUE/////////////////////////////
////ref- https://www.geeksforgeeks.org/window-sliding-technique/////////////////////////////
#include <bits/stdc++.h>
using namespace std;
#define beastslayer ios_base::sync_with_stdio(false);cin.tie(NULL);
#define ll long long

//Q- Find the maximum sum of a k length subarray from a given array

int main()
{
beastslayer;

int arr[10]={5,1,-9,2,3,5,7,11,12,50};
int k; //Length of subarrays
cin>>k;

int max_sum=0; //Final answer to be found
for(int i=0;i<k;++i)
max_sum+=arr[i];

int window_sum=max_sum; //current window pane sum

for(int i=k;i<10;++i)
{
window_sum+=arr[i]-arr[i-k]; //going to every element and removing the one (i-k)th for creating new pale window
max_sum=max(window_sum,max_sum);
}
cout<<max_sum<<endl;

return 0;
}
23 changes: 23 additions & 0 deletions algorithms/greedy/Kadane_Algorithm.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
//Max subarray sum using Kadanes algorithm

#include <iostream>
using namespace std;

int main()
{
int arr_size; cin>>arr_size;
int arr[arr_size];
for(int i=0;i<arr_size;++i) cin>>arr[i];

int ma=0,ans=INT_MIN;
for(int i=0;i<arr_size;++i){
ma+=arr[i];
if(ma>ans){
ans=ma;
}
if(ma<0) ma=0;
}
cout<<ans<<endl;

return 0;
}