- 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
- 38 lines of C++ from the credited upstream file 1981.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 minimizeTheDifference(vector<vector<int>>& mat, int target) {4 const int minSum = getMinSum(mat);5 if (minSum >= target) 6 return minSum - target;7 8 const int maxSum = getMaxSum(mat);9 vector<vector<int>> mem(mat.size(), vector<int>(maxSum + 1, -1));10 return minimizeTheDifference(mat, 0, 0, target, mem);11 }12 13 private:14 int minimizeTheDifference(const vector<vector<int>>& mat, int i, int sum,15 int target, vector<vector<int>>& mem) {16 if (i == mat.size())17 return abs(sum - target);18 if (mem[i][sum] != -1)19 return mem[i][sum];20 int res = INT_MAX;21 for (const int num : mat[i])22 res = min(res, minimizeTheDifference(mat, i + 1, sum + num, target, mem));23 return mem[i][sum] = res;24 }25 26 int getMinSum(const vector<vector<int>>& mat) {27 return accumulate(28 mat.begin(), mat.end(), 0,29 [](int acc, const vector<int>& row) { return acc + ranges::min(row); });30 }31 32 int getMaxSum(const vector<vector<int>>& mat) {33 return accumulate(34 mat.begin(), mat.end(), 0,35 [](int acc, const vector<int>& row) { return acc + ranges::max(row); });36 }37};38