- 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
- 30 lines of Java from the credited upstream file 3366.java.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks 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 int minArraySum(int[] nums, int k, int op1, int op2) {3 Integer[][][] mem = new Integer[nums.length][op1 + 1][op2 + 1];4 return minArraySum(nums, 0, op1, op2, k, mem);5 }6 7 8 9 private int minArraySum(int[] nums, int i, int op1, int op2, int k, Integer[][][] mem) {10 if (i == nums.length)11 return 0;12 if (mem[i][op1][op2] != null)13 return mem[i][op1][op2];14 int res = nums[i] + minArraySum(nums, i + 1, op1, op2, k, mem);15 if (op1 > 0)16 res = Math.min(res, (nums[i] + 1) / 2 + minArraySum(nums, i + 1, op1 - 1, op2, k, mem));17 if (op2 > 0 && nums[i] >= k)18 res = Math.min(res, nums[i] - k + minArraySum(nums, i + 1, op1, op2 - 1, k, mem));19 if (op1 > 0 && op2 > 0) {20 if ((nums[i] + 1) / 2 >= k)21 res = Math.min(res,22 (nums[i] + 1) / 2 - k + minArraySum(nums, i + 1, op1 - 1, op2 - 1, k, mem));23 if (nums[i] >= k)24 res = Math.min(res,25 (nums[i] - k + 1) / 2 + minArraySum(nums, i + 1, op1 - 1, op2 - 1, k, mem));26 }27 return mem[i][op1][op2] = res;28 }29}30