Skip to content

3522. Calculate Score After Performing Instructions 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  long long calculateScore(vector<string>& instructions, vector<int>& values) {
    const int n = instructions.size();
    long ans = 0;
    int i = 0;
    vector<bool> seen(n);

    while (i >= 0 && i < n && !seen[i]) {
      seen[i] = true;
      if (instructions[i] == "add") {
        ans += values[i];
        ++i;
      } else if (instructions[i] == "jump") {
        i += values[i];
      }
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public long calculateScore(String[] instructions, int[] values) {
    final int n = instructions.length;
    long ans = 0;
    int i = 0;
    boolean[] seen = new boolean[n];

    while (i >= 0 && i < n && !seen[i]) {
      seen[i] = true;
      if (instructions[i].equals("add")) {
        ans += values[i];
        ++i;
      } else if (instructions[i].equals("jump")) {
        i += values[i];
      }
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def calculateScore(self, instructions: list[str], values: list[int]) -> int:
    n = len(instructions)
    ans = 0
    i = 0
    seen = set()

    while 0 <= i < n and i not in seen:
      seen.add(i)
      if instructions[i] == 'add':
        ans += values[i]
        i += 1
      elif instructions[i] == 'jump':
        i += values[i]

    return ans