Advertisement
nikunjsoni

1690

Jun 11th, 2021
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.86 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int stoneGameVII(vector<int>& stones) {
  4.         int n = stones.size();
  5.         int prefix[n];
  6.         int dp[n][n];
  7.         memset(dp, 0, sizeof dp);
  8.        
  9.         // Calculate prefix sum.
  10.         prefix[0] = stones[0];
  11.         for(int i=1; i<n; i++)
  12.             prefix[i] = stones[i]+prefix[i-1];
  13.        
  14.         // Apply mcm logic and get answer for each [start, end] pair.
  15.         for(int length=2; length<=n; length++){
  16.             for(int start=0; start<(n-length+1); start++){
  17.                 int end = start+length-1;
  18.                 int removeFirst = prefix[end]-prefix[start];
  19.                 int removeLast = prefix[end-1]-((start-1)>=0 ? prefix[start-1] : 0);
  20.                 dp[start][end] = max(removeFirst-dp[start+1][end], removeLast-dp[start][end-1]);
  21.             }
  22.         }
  23.         return dp[0][n-1];
  24.     }
  25. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement