- 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
- 31 lines of Java from the credited upstream file 3077.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 long maximumStrength(int[] nums, int k) {3 Long[][][] mem = new Long[nums.length][k + 1][2];4 return maximumStrength(nums, 0, k, true, mem);5 }6 7 private static final long MIN = Long.MIN_VALUE / 2;8 9 10 11 private long maximumStrength(int[] nums, int i, int k, boolean fresh, Long[][][] mem) {12 if (nums.length - i < k)13 return MIN;14 if (k == 0)15 return 0;16 if (i == nums.length)17 return k == 0 ? 0 : MIN;18 if (mem[i][k][fresh ? 1 : 0] != null)19 return mem[i][k][fresh ? 1 : 0];20 21 22 23 final long skip = fresh ? maximumStrength(nums, i + 1, k, true, mem) : MIN;24 final long gain = (k % 2 == 0 ? -1 : 1) * 1L * nums[i] * k;25 final long includeAndContinue = maximumStrength(nums, i + 1, k, false, mem) + gain;26 final long includeAndFreshStart = maximumStrength(nums, i + 1, k - 1, true, mem) + gain;27 return mem[i][k][fresh ? 1 : 0] =28 Math.max(skip, Math.max(includeAndContinue, includeAndFreshStart));29 }30}31