Code:
1 class Solution { 2 public: 3 int maxCoins(vector<int>& nums) { 4 vector<int> arr; 5 arr.push_back(1); 6 for(int i:nums){ 7 arr.push_back(i); 8 } 9 arr.push_back(1); 10 vector<vector<int>> dp(arr.size(),vector<int>(arr.size(),-1)); 11 return dfs(arr,0,arr.size()-1,dp); 12 } 13 14 int dfs(vector<int> &arr, int left, int right, vector<vector<int>> &dp){ 15 if(left+1==right) return 0; 16 if(dp[left][right]!=-1) return dp[left][right]; 17 int res=0; 18 for(int i=left+1;i<right;++i){ 19 res=max(res,arr[left]*arr[i]*arr[right]+dfs(arr,left,i,dp)+dfs(arr,i,right,dp)); 20 } 21 return dp[left][right]=res; 22 } 23 };