Ctrl K

Spells Without Neighbors

Medium
A wizard has a set of spells, where damage[i] is the damage of spell i. Several spells may deal the same damage. Each spell can be cast at most once. However, once the wizard casts a spell dealing x damage, spells dealing x - 2, x - 1, x + 1 or x + 2 become off limits. Other spells dealing exactly x are still allowed. Return the largest total damage the wizard can deal.
Example 1
damage=[2, 2, 4, 5, 9] → 18

Take both 2s, the 5 and the 9: 2 + 2 + 5 + 9 = 18. The 4 is off limits since it is within 2 of both 2 and 5.

Example 2
damage=[3, 4, 5, 6] → 9

Only 3 and 6 are far enough apart to go together, giving 9.

Example 3
damage=[10] → 10
Constraints
  • 1 ≤ len(damage) ≤ 10⁵
  • 1 ≤ damage[i] ≤ 10⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsPairs With a Fixed Gap MediumWords Hidden in a Text MediumTriples Hitting the Target MediumWord Growth Chain MediumShuttle Driver Earnings Medium
loading Python…
Input
damage=[2, 2, 4, 5, 9]
Expected
18

Run checks the first 3 tests in your browser. Submit checks all 102 tests on the server, hidden ones included.