[LeetCode] Defuse the Bomb

1652. Defuse the Bomb

You have a bomb to defuse, and your time is running out! Your informer will provide you with a circular array code of length of n and a key k.

To decrypt the code, you must replace every number. All the numbers are replaced simultaneously.

  • If k > 0, replace the ith number with the sum of the next k numbers.
  • If k < 0, replace the ith number with the sum of the previous k numbers.
  • If k == 0, replace the ith number with 0.

As code is circular, the next element of code[n-1] is code[0], and the previous element of code[0] is code[n-1].

Given the circular array code and an integer key k, return the decrypted code to defuse the bomb!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
vector<int> decrypt(vector<int>& code, int k) {
int n = code.size();
vector<int> res;
for(int i = 0; i < n; i++) {
int now = 0;
if(k > 0) {
for(int j = 0; j < k; j++) now = (now + code[(1+i+j)%n]);
} else if(k < 0) {
for(int j = 0; j < -k; j++) now = (now + code[(i-j-1+n)%n]);
}
res.push_back(now);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/11/18/PS/LeetCode/defuse-the-bomb/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.