LeetCode #3771 — MEDIUM

Total Score of Dungeon Runs

Move from brute-force thinking to an efficient approach using array strategy.

Solve on LeetCode
The Problem

Problem Statement

You are given a positive integer hp and two positive 1-indexed integer arrays damage and requirement.

There is a dungeon with n trap rooms numbered from 1 to n. Entering room i reduces your health points by damage[i]. After that reduction, if your remaining health points are at least requirement[i], you earn 1 point for that room.

Let score(j) be the number of points you get if you start with hp health points and enter the rooms j, j + 1, ..., n in this order.

Return the integer score(1) + score(2) + ... + score(n), the sum of scores over all starting rooms.

Note: You cannot skip rooms. You can finish your journey even if your health points become non-positive.

Example 1:

Input: hp = 11, damage = [3,6,7], requirement = [4,2,5]

Output: 3

Explanation:

score(1) = 2, score(2) = 1, score(3) = 0. The total score is 2 + 1 + 0 = 3.

As an example, score(1) = 2 because you get 2 points if you start from room 1.

  • You start with 11 health points.
  • Enter room 1. Your health points are now 11 - 3 = 8. You get 1 point because 8 >= 4.
  • Enter room 2. Your health points are now 8 - 6 = 2. You get 1 point because 2 >= 2.
  • Enter room 3. Your health points are now 2 - 7 = -5. You do not get any points because -5 < 5.

Example 2:

Input: hp = 2, damage = [10000,1], requirement = [1,1]

Output: 1

Explanation:

score(1) = 0, score(2) = 1. The total score is 0 + 1 = 1.

score(1) = 0 because you do not get any points if you start from room 1.

  • You start with 2 health points.
  • Enter room 1. Your health points are now 2 - 10000 = -9998. You do not get any points because -9998 < 1.
  • Enter room 2. Your health points are now -9998 - 1 = -9999. You do not get any points because -9999 < 1.

score(2) = 1 because you get 1 point if you start from room 2.

  • You start with 2 health points.
  • Enter room 2. Your health points are now 2 - 1 = 1. You get 1 point because 1 >= 1.

Constraints:

  • 1 <= hp <= 109
  • 1 <= n == damage.length == requirement.length <= 105
  • 1 <= damage[i], requirement[i] <= 104
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: You are given a positive integer hp and two positive 1-indexed integer arrays damage and requirement. There is a dungeon with n trap rooms numbered from 1 to n. Entering room i reduces your health points by damage[i]. After that reduction, if your remaining health points are at least requirement[i], you earn 1 point for that room. Let score(j) be the number of points you get if you start with hp health points and enter the rooms j, j + 1, ..., n in this order. Return the integer score(1) + score(2) + ... + score(n), the sum of scores over all starting rooms. Note: You cannot skip rooms. You can finish your journey even if your health points become non-positive.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Array · Binary Search

Example 1

11
[3,6,7]
[4,2,5]

Example 2

2
[10000,1]
[1,1]
Step 02

Core Insight

What unlocks the optimal approach

  • Use prefix sums on the damage. Create <code>pref</code> with the prefix sums.
  • Initially, the total points/score is the total number of subarrays <code>n * (n + 1) / 2</code>.
  • We need to subtract subarrays <code>[i, j]</code> that do not satisfy <code>hp - (pref[j] - pref[i-1]) >= requirement[j]</code>. The inequality is equivalent to <code>pref[i-1] >= requirement[j] - hp + pref[j]</code>.
  • For each <code>j</code>, count the previous <code>i</code>s with <code>pref[i-1] < requirement[j] - hp + pref[j]</code> using binary search or an ordered data structure.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3771: Total Score of Dungeon Runs
// Auto-generated Java example from go.
class Solution {
    public void exampleSolution() {
    }
}
// Reference (go):
// // Accepted solution for LeetCode #3771: Total Score of Dungeon Runs
// package main
// 
// import "sort"
// 
// // https://space.bilibili.com/206214
// func totalScore1(hp int, damage []int, requirement []int) (ans int64) {
// 	sum := make([]int, len(damage)+1)
// 	for i, req := range requirement {
// 		sum[i+1] = sum[i] + damage[i]
// 		low := sum[i+1] + req - hp
// 		j := sort.SearchInts(sum[:i+1], low)
// 		ans += int64(i - j + 1)
// 	}
// 	return
// }
// 
// func totalScore(hp int, damage, requirement []int) int64 {
// 	n := len(damage)
// 	sum := make([]int, n+1)
// 	ans := n * (n + 1) / 2
// 	for i, req := range requirement {
// 		sum[i+1] = sum[i] + damage[i]
// 		low := sum[i+1] + req - hp
// 		if low > 0 {
// 			ans -= sort.SearchInts(sum[:i+1], low)
// 		}
// 	}
// 	return int64(ans)
// }
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(log n)
Space
O(1)

Approach Breakdown

LINEAR SCAN
O(n) time
O(1) space

Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.

BINARY SEARCH
O(log n) time
O(1) space

Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).

Shortcut: Halving the input each step → O(log n). Works on any monotonic condition, not just sorted arrays.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

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.

Boundary update without `+1` / `-1`

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.