Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Algorithm] MaxCounters #136

Closed
hwangJi-dev opened this issue Mar 22, 2023 · 0 comments
Closed

[Algorithm] MaxCounters #136

hwangJi-dev opened this issue Mar 22, 2023 · 0 comments

Comments

@hwangJi-dev
Copy link
Owner

hwangJi-dev commented Mar 22, 2023

💬 문제

https://app.codility.com/programmers/lessons/4-counting_elements/max_counters/


💬 Idea

  • maxCounter로 바꾸는 시점에서 Array(repeating:, count:) 메서드를 사용했더니 시간 초과가 발생했다.
  • 시간 초과를 해결하기 위해 많은 시간이 걸렸다.. ㅠㅠ
  • 해결 로직
    • increase: maxCounterValue보다 현재 counter가 작다면 counter를 maxCounterValue로 변경해주고 그 이후에 +1 작업을 수행한다.
    • maxcounter로 모두 변경 메서드: 반복문 이후에 일괄 수행한다.

💬 풀이

import Foundation

public func solution(N : Int, A : inout [Int]) -> [Int] {
    var counter = Array(repeating: 0, count: N)
    var maxCounter = 0
    var maxCounterValue = 0
    
    for a in A {
        if a == N + 1 {
            maxCounterValue = maxCounter
        } else {
            if counter[a - 1] < maxCounterValue {
                counter[a - 1] = maxCounterValue
            }
            
            counter[a - 1] += 1
            
            if maxCounter < counter[a - 1] {
                maxCounter = counter[a - 1]
            }
        }
    }
    
    for i in 0..<counter.count {
        if counter[i] < maxCounterValue {
            counter[i] = maxCounterValue
        }
    }
    
    return counter
}

소요시간 : 1시간

시간 복잡도 : O(N + M)

평가표 : https://app.codility.com/demo/results/trainingW968PA-XQX/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant