Leetcode 1652. Defuse the Bomb
You have a bomb to defuse, and your experience tells you that defusing it will be much easier once you understand the code used to create this bomb.
You are given an integer array code
and an integer k
. The array code
is of length n
and is indexed from 0
to n - 1
. The rounding rule for calculating the array value at index i
is as follows:
k > 0
, replace the element at index i
with the sum of the next k
elements.k < 0
, replace the element at index i
with the sum of the previous |k|
elements.k == 0
, replace the element at index i
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]
.
Return the transformed array code
into the new array as described above.
k
?
k
can be any integer between -n
and n
inclusive.n
?
n
will be between 1
and 10000
.k == 0
, return an array of zeroes of the same length as code
.k
elements based on the value of k
.#include <vector>
using namespace std;
vector<int> decrypt(vector<int>& code, int k) {
int n = code.size();
vector<int> result(n, 0);
if (k == 0) {
return result;
}
int start = k > 0 ? 1 : k;
int end = k > 0 ? k : -1;
int current_sum = 0;
// Initial window sum calculation
for (int i = start; i <= end; ++i) {
current_sum += code[(i + n) % n];
}
for (int i = 0; i < n; ++i) {
result[i] = current_sum;
// Slide window right
current_sum -= code[(i + start + n) % n];
current_sum += code[(i + end + 1 + n) % n];
}
return result;
}
k == 0
.k
is positive or negative, set up the initial sum of the window.By following this approach, we ensure that the array is correctly transformed as per the problem’s requirements in an efficient manner.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?