Leetcode Problem:
Summary
- A circular array code of length n and a key k are given
- The goal is to decrypt the code by replacing every number with the sum of the next k numbers if k is positive, the sum of the previous k numbers if k is negative, and 0 if k is 0.
Approach
- The approach used is to iterate through the array and for each element, calculate the sum of the next k numbers if k is positive, the sum of the previous k numbers if k is negative, and 0 if k is 0
- The sum is then appended to the result vector.
Complexity
- O(n * |k|) where n is the length of the code array and |k| is the absolute value of the key k.
Solution Code:
class Solution {
public:
vector decrypt(vector& code, int k) {
vector ans;
int N = code.size();
for(int i = 0 ; i < N; i++){
int sum = 0;
for(int j = 1; j <= abs(k); j++){
int idx;
if (k > 0){
idx = (i + j) % N;
} else if(k < 0) {
idx = (i - j + N) % N;
} else{
break;
}
sum += code[idx];
}
ans.push_back(sum);
}
return ans;
}
};
'알고리즘' 카테고리의 다른 글
Take K of Each Character From Left and Right (0) | 2025.02.22 |
---|---|
Maximum Sum of Distinct Subarrays With Length K (0) | 2025.02.22 |
Shortest Subarray with Sum at Least K (0) | 2025.02.22 |
Find the Power of K-Size Subarrays I (0) | 2025.02.22 |
Find Elements in a Contaminated Binary Tree (0) | 2025.02.21 |