[LeetCode] Calculate Score After Performing Instructions

3522. Calculate Score After Performing Instructions

You are given two arrays, instructions and values, both of size n.

You need to simulate a process based on the following rules:

  • You start at the first instruction at index i = 0 with an initial score of 0.

  • If instructions[i] is "add" :

    • Add values[i] to your score.
    • Move to the next instruction (i + 1).
  • If instructions[i] is "jump" :

    • Move to the instruction at index (i + values[i]) without modifying your score.

The process ends when you either:

  • Go out of bounds (i.e., i < 0 or i >= n), or
  • Attempt to revisit an instruction that has been previously executed. The revisited instruction is not executed.

Return your score at the end of the process.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
long long calculateScore(vector<string>& instructions, vector<int>& values) {
long long idx = 0, res = 0, n = values.size();
vector<bool> vis(n);
while(0 <= idx and idx < n and !vis[idx]) {
vis[idx] = true;
if(instructions[idx] == "add") {
res += values[idx++];
} else idx += values[idx];
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/04/20/PS/LeetCode/calculate-score-after-performing-instructions/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.