- 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
- 42 lines of Java from the credited upstream file 3186.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup, cached states.
- 2 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 long maximumTotalDamage(int[] power) {3 Map<Integer, Integer> count = new HashMap<>();4 5 for (final int damage : power)6 count.merge(damage, 1, Integer::sum);7 8 List<Integer> uniqueDamages = getSortedUniqueDamages(count);9 final int n = uniqueDamages.size();10 11 12 long[][] dp = new long[n][2];13 14 for (int i = 0; i < n; ++i) {15 final int damage = uniqueDamages.get(i);16 if (i == 0) {17 dp[0][0] = 0;18 dp[0][1] = (long) damage * count.get(damage);19 continue;20 }21 dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1]);22 dp[i][1] = (long) damage * count.get(damage);23 if (i >= 1 && uniqueDamages.get(i - 1) != damage - 1 &&24 uniqueDamages.get(i - 1) != damage - 2) {25 dp[i][1] += Math.max(dp[i - 1][0], dp[i - 1][1]);26 } else if (i >= 2 && uniqueDamages.get(i - 2) != damage - 2) {27 dp[i][1] += Math.max(dp[i - 2][0], dp[i - 2][1]);28 } else if (i >= 3) {29 dp[i][1] += Math.max(dp[i - 3][0], dp[i - 3][1]);30 }31 }32 33 return Math.max(dp[n - 1][0], dp[n - 1][1]);34 }35 36 private List<Integer> getSortedUniqueDamages(Map<Integer, Integer> count) {37 List<Integer> uniqueDamages = new ArrayList<>(count.keySet());38 Collections.sort(uniqueDamages);39 return uniqueDamages;40 }41}42