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

Create PotsOfGold.cpp #1617

Open
wants to merge 1 commit into
base: dev
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
40 changes: 40 additions & 0 deletions Dynamic Programming/Pots of Gold/cpp/PotsOfGold.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// Full problem Statement: https://practice-stage.geeksforgeeks.org/problems/pots-of-gold-game/1

#include <bits/stdc++.h>
using namespace std;

int maxCoins(int A[],int N)
{
int n=N;
int dp[N][N];
memset(dp,0,sizeof(dp));
for(int gap=0;gap<n;gap++){
for(int i=0,j=i+gap;i<n && j<n;i++,j++){
if(gap==0)
dp[i][j]=A[i];
else if(gap==1)
dp[i][j] = max(A[i],A[j]);
else{
dp[i][j] = max(A[i]+min(dp[i+2][j],dp[i+1][j-1]),
min(dp[i][j-2],dp[i+1][j-1])+A[j]);
}
}

}
return dp[0][n-1];
}

int main() {
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
cin>>a[i];
cout<<maxCoins(a,n)<<endl;
}
return 0;
}