koenjazh-CNfresde
짬뽕얼큰하게의 맨땅에 헤딩 :: Defuse the Bomb

Defuse the Bomb

알고리즘 2025. 2. 22. 08:42

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;
    }
};
블로그 이미지

짬뽕얼큰하게

,