[코딜리티] 레슨 4 - MaxCounters (Swift)

devapploper·2024년 8월 11일

풀이1

public func solution(_ N : Int, _ A : inout [Int]) -> [Int] {
    var counters = [Int](repeating: 0, count: N)
    var (maxValue, maxCount) = (0, 0)

    for number in A {
        if number <= N {
            if counters[number-1] < maxValue {
                counters[number-1] = maxValue
            }
            counters[number-1] += 1
            maxCount = max(maxCount, counters[number-1])
        } else if number == N+1 {
            maxValue = maxCount
        }
    }

    for i in 0..<counters.count {
        if counters[i] < maxValue {
            counters[i] = maxValue
        }
    }

    return counters
}

maxCounter 작업을 후처리한 이후에 속도가 개선되어 통과함.

profile
iOS, 알고리즘, 컴퓨터공학에 관련 포스트를 정리해봅니다

0개의 댓글