Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
A magician has various spells.
You are given an array power, where each element represents the damage of a spell. Multiple spells can have the same damage value.
It is a known fact that if a magician decides to cast a spell with a damage of power[i], they cannot cast any spell with a damage of power[i] - 2, power[i] - 1, power[i] + 1, or power[i] + 2.
Each spell can be cast only once.
Return the maximum possible total damage that a magician can cast.
Example 1:
Input: power = [1,1,3,4]
Output: 6
Explanation:
The maximum possible damage of 6 is produced by casting spells 0, 1, 3 with damage 1, 1, 4.
Example 2:
Input: power = [7,1,6,6]
Output: 13
Explanation:
The maximum possible damage of 13 is produced by casting spells 1, 2, 3 with damage 1, 6, 6.
Constraints:
1 <= power.length <= 1051 <= power[i] <= 109Problem summary: A magician has various spells. You are given an array power, where each element represents the damage of a spell. Multiple spells can have the same damage value. It is a known fact that if a magician decides to cast a spell with a damage of power[i], they cannot cast any spell with a damage of power[i] - 2, power[i] - 1, power[i] + 1, or power[i] + 2. Each spell can be cast only once. Return the maximum possible total damage that a magician can cast.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Two Pointers · Binary Search · Dynamic Programming
[1,1,3,4]
[7,1,6,6]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3186: Maximum Total Damage With Spell Casting
class Solution {
private Long[] f;
private int[] power;
private Map<Integer, Integer> cnt;
private int[] nxt;
private int n;
public long maximumTotalDamage(int[] power) {
Arrays.sort(power);
this.power = power;
n = power.length;
f = new Long[n];
cnt = new HashMap<>(n);
nxt = new int[n];
for (int i = 0; i < n; ++i) {
cnt.merge(power[i], 1, Integer::sum);
int l = Arrays.binarySearch(power, power[i] + 3);
l = l < 0 ? -l - 1 : l;
nxt[i] = l;
}
return dfs(0);
}
private long dfs(int i) {
if (i >= n) {
return 0;
}
if (f[i] != null) {
return f[i];
}
long a = dfs(i + cnt.get(power[i]));
long b = 1L * power[i] * cnt.get(power[i]) + dfs(nxt[i]);
return f[i] = Math.max(a, b);
}
}
// Accepted solution for LeetCode #3186: Maximum Total Damage With Spell Casting
func maximumTotalDamage(power []int) int64 {
n := len(power)
sort.Ints(power)
cnt := map[int]int{}
nxt := make([]int, n)
f := make([]int64, n)
for i, x := range power {
cnt[x]++
nxt[i] = sort.SearchInts(power, x+3)
}
var dfs func(int) int64
dfs = func(i int) int64 {
if i >= n {
return 0
}
if f[i] != 0 {
return f[i]
}
a := dfs(i + cnt[power[i]])
b := int64(power[i]*cnt[power[i]]) + dfs(nxt[i])
f[i] = max(a, b)
return f[i]
}
return dfs(0)
}
# Accepted solution for LeetCode #3186: Maximum Total Damage With Spell Casting
class Solution:
def maximumTotalDamage(self, power: List[int]) -> int:
@cache
def dfs(i: int) -> int:
if i >= n:
return 0
a = dfs(i + cnt[power[i]])
b = power[i] * cnt[power[i]] + dfs(nxt[i])
return max(a, b)
n = len(power)
cnt = Counter(power)
power.sort()
nxt = [bisect_right(power, x + 2, lo=i + 1) for i, x in enumerate(power)]
return dfs(0)
// Accepted solution for LeetCode #3186: Maximum Total Damage With Spell Casting
use std::collections::HashMap;
impl Solution {
pub fn maximum_total_damage(mut power: Vec<i32>) -> i64 {
power.sort();
let n = power.len();
let mut cnt = HashMap::new();
let mut nxt = vec![0; n];
let mut f = vec![-1_i64; n];
for i in 0..n {
*cnt.entry(power[i]).or_insert(0) += 1;
let j = match power[i + 1..].binary_search_by(|&x| x.cmp(&(power[i] + 2 + 1))) {
Ok(pos) | Err(pos) => i + 1 + pos,
};
nxt[i] = j;
}
fn dfs(
i: usize,
n: usize,
power: &Vec<i32>,
nxt: &Vec<usize>,
f: &mut Vec<i64>,
cnt: &HashMap<i32, i32>,
) -> i64 {
if i >= n {
return 0;
}
if f[i] != -1 {
return f[i];
}
let c = *cnt.get(&power[i]).unwrap();
let a = dfs(i + c as usize, n, power, nxt, f, cnt);
let b = power[i] as i64 * c as i64 + dfs(nxt[i], n, power, nxt, f, cnt);
f[i] = a.max(b);
f[i]
}
dfs(0, n, &power, &nxt, &mut f, &cnt)
}
}
// Accepted solution for LeetCode #3186: Maximum Total Damage With Spell Casting
function maximumTotalDamage(power: number[]): number {
const n = power.length;
power.sort((a, b) => a - b);
const f: number[] = Array(n).fill(0);
const cnt: Record<number, number> = {};
const nxt: number[] = Array(n).fill(0);
for (let i = 0; i < n; ++i) {
cnt[power[i]] = (cnt[power[i]] || 0) + 1;
let [l, r] = [i + 1, n];
while (l < r) {
const mid = (l + r) >> 1;
if (power[mid] > power[i] + 2) {
r = mid;
} else {
l = mid + 1;
}
}
nxt[i] = l;
}
const dfs = (i: number): number => {
if (i >= n) {
return 0;
}
if (f[i]) {
return f[i];
}
const a = dfs(i + cnt[power[i]]);
const b = power[i] * cnt[power[i]] + dfs(nxt[i]);
return (f[i] = Math.max(a, b));
};
return dfs(0);
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair of elements. The outer loop picks one element, the inner loop scans the rest. For n elements that is n × (n−1)/2 comparisons = O(n²). No extra memory — just two loop variables.
Each pointer traverses the array at most once. With two pointers moving inward (or both moving right), the total number of steps is bounded by n. Each comparison is O(1), giving O(n) overall. No auxiliary data structures are needed — just two index variables.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Advancing both pointers shrinks the search space too aggressively and skips candidates.
Usually fails on: A valid pair can be skipped when only one side should move.
Fix: Move exactly one pointer per decision branch based on invariant.
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.