[LeetCode] 3190. Find Minimum Operations to Make All Elements Divisible by Three

Chobby·2025년 12월 25일

LeetCode

목록 보기
870/890

😎풀이

  1. 3의 배수를 적절히 저장 (nums[i]는 50 까지만 존재함을 활용)
  2. nums 순회
    2-1. 3으로 나눈 몫을 통해 가장 가까운 3의 배수 확인
    2-2. 두 배수 중 더 가까운 수로 변환
    2-3. 변환에 필요한 연산의 수 누적
  3. 모든 수를 3의 배수로 변환하는데 필요한 최소 연산 수 반환환
function minimumOperations(nums: number[]): number {
    let operation = 0
    const threes = [0]
    for(let i = 3; i <= 53; i += 3) threes.push(i)
    for(const num of nums) {
        const quot = Math.floor(num / 3)
        const first = threes[quot] ?? 0
        const second = threes[quot + 1] ?? 0
        const firstGap = Math.abs(first - num)
        const secondGap = Math.abs(second - num)
        operation += Math.min(firstGap, secondGap)
    }

    return operation
};
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글