- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 41 lines of C++ from the credited upstream file 1563.cpp.
- The implementation visibly relies on sequence storage.
- 1 loop block detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int stoneGameV(vector<int>& stoneValue) {4 const int n = stoneValue.size();5 vector<vector<int>> mem(n, vector<int>(n, INT_MIN));6 vector<int> prefix(n + 1);7 partial_sum(stoneValue.begin(), stoneValue.end(), prefix.begin() + 1);8 return stoneGameV(stoneValue, 0, n - 1, prefix, mem);9 }10 11 private:12 13 int stoneGameV(const vector<int>& stoneValue, int i, int j,14 const vector<int>& prefix, vector<vector<int>>& mem) {15 if (i == j)16 return 0;17 if (mem[i][j] > 0)18 return mem[i][j];19 20 21 for (int p = i; p < j; ++p) {22 23 const int leftSum = prefix[p + 1] - prefix[i];24 const int throwRight =25 leftSum + stoneGameV(stoneValue, i, p, prefix, mem);26 27 const int rightSum = prefix[j + 1] - prefix[p + 1];28 const int throwLeft =29 rightSum + stoneGameV(stoneValue, p + 1, j, prefix, mem);30 if (leftSum < rightSum) 31 mem[i][j] = max(mem[i][j], throwRight);32 else if (leftSum > rightSum) 33 mem[i][j] = max(mem[i][j], throwLeft);34 else 35 mem[i][j] = max({mem[i][j], throwLeft, throwRight});36 }37 38 return mem[i][j];39 }40};41