Dungeon Runs

You are given an initial health value, hp, and two integer arrays of length n: damage and requirement.

A dungeon consists of n sequential rooms indexed from 0 to n - 1. When you enter room i, the following events occur in order:

  • Your current health immediately decreases by damage[i].
  • If your remaining health is >= requirement[i], you earn exactly 1 point.
  • You must continue to the next room regardless of your health status (even if it drops to 0 or becomes negative).

Let score(j) be the total points collected if you begin your journey at room j and proceed strictly rightwards until completing the final room (n - 1). Important: Your health resets to the full initial hp every time you start at a new room j.

Return the sum of score(j) for all possible starting rooms j from 0 to n - 1.

Example 1:

Input: hp = 15, damage = [10, 4, 1], requirement = [5, 10, 2]

Output: 4

Explanation: We calculate the score for each starting room. Starting at room 0: you enter room 0 (hp becomes 5, matching the requirement of 5, earning 1 point), enter room 1 (hp drops to 1, failing the requirement of 10), and enter room 2 (hp drops to 0, failing the requirement of 2), yielding score(1) = 1. Starting at room 1: you enter room 2 (hp becomes 11, passing the requirement of 10, earning 1 point) and enter room 2 (hp becomes 10, passing the requirement of 2, earning 1 point), yielding score(2) = 2. Starting at room 2: you enter room 2 (hp becomes 14, passing the requirement of 2, earning 1 point), yielding score(3) = 1. The total sum is 1 + 2 + 1 = 4.

Example 2:

Input: hp = 5, damage = [2, 10, 1], requirement = [1, 2, 1]

Output: 2

Explanation: Starting at room 0: entering room 0 leaves you with 3 hp, satisfying the requirement of 1 (1 point). Entering room 1 plunges your hp to -7, missing the requirement. Entering room 2 drops your hp to -8, missing the requirement again, making score(1) = 1. Starting at room 1: entering room 2 drops your hp from 5 directly to -5, and continuing to room 2 drops it further to -6, earning no points, making score(2) = 0. Starting at room 2: entering room 2 leaves you with 4 hp, satisfying the requirement of 1, making score(3) = 1. The total score across all runs is 1 + 0 + 1 = 2.

Now Your Turn!

Pick the correct output for the given input

Input: hp = 50, damage = [5, 5, 5], requirement = [10, 10, 10]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

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

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
long long totalScore(int hp, vector<int>& damage, vector<int>& requirement) {
// Write your code here
}
}
Test Case

Input:

Damage
Hp
Requirement