Medium
You are given two arrays, instructions
and values
, both of size n
.
You need to simulate a process based on the following rules:
i = 0
with an initial score of 0.instructions[i]
is "add"
:
values[i]
to your score.(i + 1)
.instructions[i]
is "jump"
:
(i + values[i])
without modifying your score.The process ends when you either:
i < 0 or i >= n
), orReturn your score at the end of the process.
Example 1:
Input: instructions = [“jump”,”add”,”add”,”jump”,”add”,”jump”], values = [2,1,3,1,-2,-3]
Output: 1
Explanation:
Simulate the process starting at instruction 0:
"jump"
, move to index 0 + 2 = 2
."add"
, add values[2] = 3
to your score and move to index 3. Your score becomes 3."jump"
, move to index 3 + 1 = 4
."add"
, add values[4] = -2
to your score and move to index 5. Your score becomes 1."jump"
, move to index 5 + (-3) = 2
.Example 2:
Input: instructions = [“jump”,”add”,”add”], values = [3,1,1]
Output: 0
Explanation:
Simulate the process starting at instruction 0:
"jump"
, move to index 0 + 3 = 3
.Example 3:
Input: instructions = [“jump”], values = [0]
Output: 0
Explanation:
Simulate the process starting at instruction 0:
"jump"
, move to index 0 + 0 = 0
.Constraints:
n == instructions.length == values.length
1 <= n <= 105
instructions[i]
is either "add"
or "jump"
.-105 <= values[i] <= 105
class Solution {
fun calculateScore(instructions: Array<String>, values: IntArray): Long {
var ans: Long = 0
val seen = BooleanArray(instructions.size)
var pos = 0
while (pos >= 0 && pos < instructions.size && !seen[pos]) {
seen[pos] = true
if (instructions[pos][0] == 'a') {
ans += values[pos].toLong()
pos++
} else {
pos += values[pos]
}
}
return ans
}
}