[LeetCode] 3354. Make Array Elements Equal to Zero

Chobby·2026년 1월 8일

LeetCode

목록 보기
896/979

😎풀이

  1. 특정 인덱스부터 원하는 방향으로 순회했을 때 모든 요소를 0으로 만들 수 있는지 검증하는 헬퍼 함수 isValidSelection 정의
  2. nums의 모든 인덱스 순회
    2-1. 0인 요소의 인덱스에서 좌측과 우측으로 이동할 경우 모든 요소를 0으로 만들 수 있는지 검증
    2-2. 가능할 경우, validSelection 증가
  3. 가능한 모든 경우의 수 반환가능한 모든 경우의 수 반환
function countValidSelections(nums: number[]): number {
    let validSelection = 0
    for(let start = 0; start < nums.length; start++) {
        if(nums[start] !== 0) continue
        if(isValidSelection([...nums], start, 1)) validSelection++
        if(isValidSelection([...nums], start, -1)) validSelection++
    }
    return validSelection
};

function isValidSelection(nums: number[], start: number, direction: number) {
    let idx = start
    while(idx >= 0 && idx < nums.length) {
        idx += direction
        if(nums[idx] > 0) {
            nums[idx]--
            direction *= -1
        }
    }
    return nums.every(num => num === 0)
}
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글