- 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
- 37 lines of Java from the credited upstream file 3473.java.
- 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 int maxSum(int[] nums, int k, int m) {3 final int n = nums.length;4 int[] prefix = new int[n + 1];5 Integer[][][] mem = new Integer[n][2][k + 1];6 for (int i = 0; i < n; i++)7 prefix[i + 1] = prefix[i] + nums[i];8 return maxSum(nums, 0, 0, k, m, prefix, mem);9 }10 11 private static final int INF = 20_000_000;12 13 private int maxSum(int[] nums, int i, int ongoing, int k, int m, int[] prefix,14 Integer[][][] mem) {15 if (k < 0)16 return -INF;17 if (i == nums.length)18 return k == 0 ? 0 : -INF;19 if (mem[i][ongoing][k] != null)20 return mem[i][ongoing][k];21 if (ongoing == 1)22 23 24 return mem[i][1][k] = Math.max(maxSum(nums, i, 0, k, m, prefix, mem),25 maxSum(nums, i + 1, 1, k, m, prefix, mem) + nums[i]);26 27 28 29 int res = maxSum(nums, i + 1, 0, k, m, prefix, mem);30 if (i + m <= nums.length) 31 res = Math.max(res,32 maxSum(nums, i + m, 1, k - 1, m, prefix, mem) + (prefix[i + m] - prefix[i]));33 34 return mem[i][0][k] = res;35 }36}37