- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 35 lines of C++ from the credited upstream file 3366-2.cpp.
- The implementation visibly relies on sequence storage, cached states.
- 5 loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
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 minArraySum(vector<int>& nums, int k, int op1, int op2) {4 const int n = nums.size();5 6 7 vector<vector<vector<int>>> dp(8 n + 1, vector<vector<int>>(op1 + 1, vector<int>(op2 + 1, INT_MAX)));9 10 11 for (int i = 0; i <= op1; ++i)12 for (int j = 0; j <= op2; ++j)13 dp[n][i][j] = 0;14 15 for (int i = n - 1; i >= 0; --i)16 for (int o1 = 0; o1 <= op1; ++o1)17 for (int o2 = 0; o2 <= op2; ++o2) {18 int sum = nums[i] + dp[i + 1][o1][o2];19 if (o1 > 0)20 sum = min(sum, (nums[i] + 1) / 2 + dp[i + 1][o1 - 1][o2]);21 if (o2 > 0 && nums[i] >= k)22 sum = min(sum, nums[i] - k + dp[i + 1][o1][o2 - 1]);23 if (o1 > 0 && o2 > 0) {24 if ((nums[i] + 1) / 2 >= k)25 sum = min(sum, (nums[i] + 1) / 2 - k + dp[i + 1][o1 - 1][o2 - 1]);26 if (nums[i] >= k)27 sum = min(sum, (nums[i] - k + 1) / 2 + dp[i + 1][o1 - 1][o2 - 1]);28 }29 dp[i][o1][o2] = sum;30 }31 32 return dp[0][op1][op2];33 }34};35