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] MinAvgTwoSlice #141

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

[Algorithm] MinAvgTwoSlice #141

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

Comments

@hwangJi-dev
Copy link
Owner

hwangJi-dev commented Mar 23, 2023

πŸ’¬Β λ¬Έμ œ

https://app.codility.com/programmers/lessons/5-prefix_sums/min_avg_two_slice/


πŸ’¬Β Idea

O(N**2)의 풀이밖에 λ– μ˜€λ₯΄μ§€ μ•Šμ•„μ„œ ν˜Ήμ‹œλ‚˜..? ν•˜κ³  μ œμΆœν•΄λ΄€μ§€λ§Œ μ—­μ‹œλ‚˜ 😊😊!!!! O(N)의 풀이여야 νš¨μœ¨μ„± ν…ŒμŠ€νŠΈλ₯Ό 톡과할 수 μžˆμ—ˆλ‹€. λ”°λΌμ„œ O(N)의 풀이λ₯Ό λ„μΆœν•˜λ € ν•΄λ΄€μ§€λ§Œ λ„μ €νžˆ O(N)의 μ‹œκ°„λ³΅μž‘λ„λ₯Ό κ°–λŠ” 풀이가 μƒκ°λ‚˜μ§€ μ•Šμ•˜λ‹€. κ·Έλž˜μ„œ λ‹€λ₯Έ λΈ”λ‘œκ·Έλ₯Ό μ°Έκ³ ν–ˆλŠ”λ°, ν‰κ· κ°’μ˜ μ›λ¦¬λΌλŠ” μˆ˜ν•™ 곡식을 μƒˆλ‘œ μ•Œκ²Œλ˜μ—ˆλ‹€ !!

ν‰κ· κ°’μ˜ 원리

πŸ’‘ κ΅¬κ°„μ˜ 평균은 λΆ€λΆ„κ΅¬κ°„μ˜ 평균 쀑 κ°€μž₯ μž‘μ€ λΆ€λΆ„κ΅¬κ°„μ˜ 평균보닀 크닀.

평균은 μ–΄λŠ 두 μˆ˜κ°€ μžˆμ„ λ•Œ κ°€μž₯ μž‘μ€ μˆ˜λ³΄λ‹€ 큰 값을 가진닀. 이 μ›λ¦¬λ‘œ μƒκ°ν•΄λ³΄μ•˜μ„ λ•Œ, μ›μ†Œκ°€ 4개인 그룹의 평균은 μ•ž 2개, λ’€ 2개둜 λ‚˜λˆ„μ–΄λ³Έλ‹€λ©΄ μ•ž λ’€ 쀑 μž‘μ€ 그룹보닀 큰 값을 κ°€μ§ˆ 것이닀. λ”°λΌμ„œ 2개인 그룹듀을 κ³ λ €ν•˜λ©΄ 4개인 그룹은 확인할 ν•„μš”κ°€ 없어진닀.

  • 짝수개둜 μͺΌκ°œμ§„ 배열듀은(2개, 4개, 6개, 8개, 10개 ,,,, λ“±μœΌλ‘œ 배열을 μŠ¬λΌμ΄μ‹±ν•œ 경우) 2개의 λΆ€λΆ„κ·Έλ£Ήλ“€λ‘œ λ‹€μ‹œ μͺΌκ°œμ§ˆ 수 있고
  • ν™€μˆ˜κ°œμ˜ 뢀뢄그룹듀은 3개 + 2개 μ‘°ν•©μ˜ λΆ€λΆ„κ·Έλ£ΉμœΌλ‘œ μͺΌκ°œμ§ˆ 수 μžˆμ„ 것이닀.
  • 3κ°œλ„ 2개 + 1개둜 μͺΌκ°œμ§ˆ 수 μžˆμ§€λ§Œ, λ¬Έμ œμ—μ„œ κ·Έλ£Ή(==뢀뢄ꡬ간)은 2κ°œλΆ€ν„° μ‹œμž‘μ΄λΌκ³  ν–ˆμœΌλ―€λ‘œ 3κ°œλŠ” μͺΌκ°œμ§ˆ 수 μ—†λ‹€.

λ”°λΌμ„œ 이 문제λ₯Ό ν’€κΈ° μœ„ν•΄μ„œ 배열을 2개, 3개둜만 μŠ¬λΌμ΄μ‹±ν•΄μ„œ 평균을 ꡬ해보면 κ°€μž₯ μž‘μ€ 평균값을 μ•Œ 수 있고, μ΅œμ†Œ μ‹œμž‘ 인덱슀 λ˜ν•œ λ„μΆœν•  수 μžˆλ‹€.


πŸ’¬Β ν’€μ΄

public func solution4(A : inout [Int]) -> Int {
    var minAvgValue: Double = Double(A[0] + A[1]) / 2
    var minIndex = 0
    
    for i in 2..<A.count {
        let avg2: Double = Double(A[i - 1] + A[i]) / 2
        if minAvgValue > avg2 {
            minAvgValue = avg2
            minIndex = i - 1
        }
        
        let avg3: Double = Double(A[i - 2] + A[i - 1] + A[i]) / 3
        if minAvgValue > avg3 {
            minAvgValue = avg3
            minIndex = i - 2
        }
    }
    
    return minIndex
}

μ‹œκ°„ λ³΅μž‘λ„ : O(N)

ν‰κ°€ν‘œ : https://app.codility.com/demo/results/training6Y3P9V-3AR/

μ½”λ”œλ¦¬ν‹°β€¦ μ°Έ μ’‹λ‹€ 😊 

<μ°Έκ³ >

https://nukeguys.tistory.com/175

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