forked from skm2000/Dynamic-Programming
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLast_Stone_3.cpp
62 lines (60 loc) · 1.59 KB
/
Last_Stone_3.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include<bits/stdc++.h>
using namespace std;
//Leetcode Question
//Recurssion base soln
int helper(vector<int>& s,int i){
if(i>=s.size()) return 0;
else{
int ans=INT_MIN;
ans=max(ans,s[i]-helper(s,i+1));
if(i+1<s.size()) ans=max(ans,s[i]+s[i+1]-helper(s,i+2));
if(i+2<s.size()) ans=max(ans,s[i]+s[i+1]+s[i+2]-helper(s,i+3));
return ans;
}
}
string stoneGameIII(vector<int>& s) {
int ans=helper(s,0);
if(ans<0) return "Bob";
else if(ans==0) return "Tie";
return "Alice";
}
//Memonization based soln
int dp[500001];
int helper(vector<int>&s,int i){
if(i>=s.size()) return 0;
if(dp[i]!=-1) return dp[i];
else{
int ans=INT_MIN;
ans=max(ans,s[i]-helper(s,i+1));
if(i+1<s.size()) ans=max(ans,s[i]+s[i+1]-helper(s,i+2));
if(i+2<s.size()) ans=max(ans,dp[i]+dp[i+1]+dp[i+2]-helper(s,i+3));
return dp[i]=ans;
}
}
string stoneGameIII(vector<int>& s) {
for(int i=0;i<s.size();i++)dp[i]=-1;
int ans=helper(s,0);
if(ans<0) return "Bob";
else if(ans==0) return "Tie";
return "Alice";
}
//Bottom Up approach
string stoneGameIII(vector<int>& s) {
int n=s.size();
vector<int>dp(n+1,0);
int i=n-1;
while(i>=0){
int ans=INT_MIN;
ans=max(ans,s[i]-dp[i+1]);
if(i+1<s.size()) ans=max(ans,s[i]+s[i+1]-dp[i+2]);
if(i+2<s.size()) ans=max(ans,s[i]+s[i+1]+s[i+2]-dp[i+3]);
dp[i]=ans;
}
int ans=dp[0];
if(ans<0) return "Bob";
else if(ans==0) return "Tie";
return "Alice";
}
int main(){
//take input
}