ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

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

 

MinAvgTwoSlice coding task - Learn to Code - Codility

Find the minimal average of any slice containing at least two elements.

app.codility.com

๋ฌธ์ œ๋ฅผ ๋ณด๋ฉด ๋ชจ๋“  ๊ตฌ๊ฐ„์— ๋Œ€ํ•ด ํ‰๊ท ์„ ๊ตฌํ•ด์•ผ ํ•  ๊ฒƒ ๊ฐ™๋‹ค. ํ•˜์ง€๋งŒ ๋ชจ๋“  ๊ตฌ๊ฐ„์— ๋Œ€ํ•œ ํ‰๊ท ์„ ๊ตฌํ•  ๊ฒฝ์šฐ ํšจ์œจ์„ฑ ๋ถ€๋ถ„์„ ํ†ต๊ณผํ•˜์ง€ ๋ชปํ•˜์—ฌ ์ ์ˆ˜๋ฅผ ๋ฐ›์ง€ ๋ชปํ•œ๋‹ค. ์„œ๋ธŒ ๊ทธ๋ฃน์—์„œ ํ‰๊ท ์„ ๊ตฌํ•  ๋•Œ์˜ ํŠน์„ฑ์„ ํ™œ์šฉํ•  ๊ฒฝ์šฐ ๋ฌธ์ œ๋ฅผ ์‰ฝ๊ฒŒ ํ•ด๊ฒฐ ํ•  ์ˆ˜ ์žˆ์œผ๋‚˜ ๊ทธ๋ ‡์ง€ ์•Š์„ ๊ฒฝ์šฐ๋Š” ํ’€์ง€ ๋ชปํ•œ๋‹ค.


๋ฌธ์ œ ํ’€์ด

์˜ˆ๋ฅผ ๋“ค์–ด ์ˆ˜๊ฐ€ 4, 2, 2, 5๊ฐ€ ์žˆ์„ ๊ฒฝ์šฐ ๊ฐ ๊ตฌ๊ฐ„์— ๋Œ€ํ•œ ํ‰๊ท ์„ ๊ตฌํ•œ๋‹ค๊ณ  ๊ฐ€์ •ํ•˜์ž

  1. ๊ตฌ๊ฐ„์ด 2์ธ ๊ฒฝ์šฐ

    1. (4 + 2) / 2 = 3

    2. (2 + 2) / 2 = 1

    3. (2 + 5) / 2 = 3.5

  2. ๊ตฌ๊ฐ„์ด 3์ธ ๊ฒฝ์šฐ

    1. (4 + 2 + 2) / 3 = 2.67 (๋ฐ˜์˜ฌ๋ฆผ)

    2. (2 + 2 + 5) / 3 = 3

  3. ๊ตฌ๊ฐ„์ด 4์ธ ๊ฒฝ์šฐ

    1. (4 + 2 + 2 + 5) / 4 = 3.25

์œ„์˜ ์˜ˆ๋Š” ๊ตฌ๊ฐ„์ด 2, 3์ธ ๊ฒฝ์šฐ๋งŒ ํ™•์ธํ•˜๋ฉด ๋” ์ด์ƒ์˜ ๊ตฌ๊ฐ„์„ ํ™•์ธํ•˜๋Š” ๊ฒƒ์€ ๋ฌด์˜๋ฏธํ•˜๋‹ค๋Š” ์„ฑ์งˆ์„ ๋ณด์—ฌ์ฃผ๋Š” ๊ฐ„๋‹จํ•œ ์˜ˆ์‹œ์ด๋‹ค. 

 


์ฝ”๋“œ

def solution(A):
    min_avg = (A[0] + A[1]) / 2
    min_idx = 0

    for i in range(2, len(A)):
        avg = (A[i - 2] + A[i - 1] + A[i]) / 3
        if min_avg > avg:
            min_avg = avg
            min_idx = i - 2

        avg = (A[i - 1] + A[i]) / 2
        if min_avg > avg:
            min_avg = avg
            min_idx = i - 1

    return min_idx
  • ๊ตฌ๊ฐ„ 2, 3์— ๋Œ€ํ•œ ํ‰๊ท  ์ค‘ ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’์— ๋Œ€ํ•ด ์ฐพ๊ณ  ์‹œ์ž‘ ์ง€์ (min_idx)๋ฅผ ์œ ์ง€ํ•œ ํ›„ ๋ฐ˜ํ™˜ํ•˜๋ฉด ๋œ๋‹ค.

728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€