#3771
Total Score of Dungeon Runs
MediumArrayBinary SearchPrefix SumPrefix SumDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Using prefix sums allows us to efficiently calculate health reductions and determine scores in linear time.
⚙️
Algorithm
3 steps- 1Step 1: Create a prefix sum array for damage to track cumulative damage up to each room.
- 2Step 2: For each room j, calculate remaining health after entering room j and subsequent rooms using the prefix sum.
- 3Step 3: Check if remaining health meets requirements and accumulate scores.
solution.py14 lines
1def totalScore(hp, damage, requirement):
2 n = len(damage)
3 prefix = [0] * n
4 prefix[0] = damage[0]
5 for i in range(1, n):
6 prefix[i] = prefix[i-1] + damage[i]
7 total = 0
8 for j in range(n):
9 health = hp - prefix[j]
10 for i in range(j, n):
11 if health >= requirement[i]:
12 total += 1
13 health -= damage[i]
14 return totalℹ
Complexity note: Prefix sums allow us to compute cumulative damage in constant time, leading to linear complexity overall.
- 1Prefix sums reduce repetitive calculations.
- 2Health points can be tracked dynamically as rooms are entered.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.