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

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

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

 

PassingCars coding task - Learn to Code - Codility

Count the number of passing cars on the road.

app.codility.com

๋ฆฌ์ŠคํŠธ ๋‚ด์˜ ์ž๋™์ฐจ ๋ฐฉํ–ฅ(east: 0 , west :1)์ด ์ฃผ์–ด์งˆ ๋•Œ, ๊ฐ ๋ฐฉํ–ฅ์ด ์Œ์„ ์ด๋ฃจ๋Š” ํšŸ์ˆ˜๋ฅผ ์ฐพ๋Š” ๋ฌธ์ œ์ด๋‹ค. ๋งŒ์•ฝ ์ธ๋ฑ์Šค 3์—์„œ east๋กœ ๊ฐ€๋Š” ์ž๋™์ฐจ๊ฐ€ ์žˆ๋‹ค๋ฉด, ์ธ๋ฑ์Šค 3 ์ดํ›„๋กœ์˜ ์ž๋™์ฐจ๋“ค๋งŒ ์Œ์„ ์ด๋ฃจ๋Š”์ง€ ํ™•์ธํ•˜๊ณ , ์•ž ๋ถ€๋ถ„์€ ํ™•์ธํ•˜์ง€ ์•Š์•„๋„ ๋œ๋‹ค.


๋ฌธ์ œ ํ’€์ด

Figure 1: ๋ฌธ์ œ์˜ ๊ธฐ๋ณธ ์˜ˆ์ œ

๊ทธ๋ฆผ 1์€ ๋ฌธ์ œ์˜ ๊ธฐ๋ณธ ์˜ˆ์ œ์—์„œ ๊ฐ’์„ ๋„์ถœํ•˜๋Š” ๊ณผ์ •์ด๋‹ค.

0 (east)๋กœ ๊ฐ€๋Š” ์ž๋™์ฐจ์™€ 1 (west)๋กœ ๊ฐ€๋Š” ์ž๋™์ฐจ๋Š” ์ง์„ ์ด๋ฃฐ ์ˆ˜ ์žˆ๋‹ค. ๋”ฐ๋ผ์„œ ๋ฆฌ์ŠคํŠธ์˜ ๊ฐ ๋ฐฉํ–ฅ์— ๋”ฐ๋ผ ์ง์„ ์ด๋ฃจ๋Š”์ง€ ํ™•์ธํ•˜๋Š” ๊ณผ์ •์€ 0์˜ ํšŸ์ˆ˜์— ๋”ฐ๋ผ ๋‹ฌ๋ผ์ง„๋‹ค.

 

๊ทธ๋ฆผ๊ณผ ๊ฐ™์ด ์ธ๋ฑ์Šค 2์—์„œ 0์ด ๋‹ค์‹œ ๋“ฑ์žฅํ•˜๋ฏ€๋กœ, ์ด์ „์˜ ๊ฐ’๊ณผ๋Š” ์Œ์„ ์ด๋ฃจ์ง€ ์•Š๊ณ  0์ด ๋ฐœ์ƒํ•œ ์ดํ›„์˜ ๊ฐ’๊ณผ ์Œ์„ ์ด๋ฃจ๋Š”์ง€ ํ™•์ธํ•˜๋Š” ๊ณผ์ •์ด ํ•„์š”ํ•˜๋‹ค. ์ฒ˜์Œ์— ์ƒ๊ฐํ–ˆ์„ ๋•Œ๋Š” 0์˜ ์œ„์น˜๋ฅผ ์ฐพ๊ณ  0์˜ ์œ„์น˜ ์ดํ›„์˜ ๊ฐ’๋“ค์„ ์ˆœ์ฐจ์ ์œผ๋กœ ํƒ์ƒ‰ํ•˜๋ฉด ๋˜์ง€ ์•Š์„๊นŒ ์ƒ๊ฐํ•˜์˜€๋‹ค. ํ•˜์ง€๋งŒ 0์ด ๋“ฑ์žฅํ•˜๋ฉด ๊ทธ๋ฆผ 1๊ณผ ๊ฐ™์ด ์นด์šดํŠธ๊ฐ€ ์ค‘๋ณต๋˜๋ฏ€๋กœ 0์˜ ํšŸ์ˆ˜์— ๋”ฐ๋ผ ์นด์šดํŠธ ์ˆ˜๋ฅผ ์ฆ๊ฐ€์‹œ์ผœ์ฃผ๋ฉด ํ•œ๋ฒˆ์˜ ํƒ์ƒ‰์œผ๋กœ ๋ชจ๋“  ์Œ์„ ์ฐพ์„ ์ˆ˜ ์žˆ๋‹ค.

 


์ฝ”๋“œ

EAST = 0
WEST = 1


def solution(A):
    answer = 0
    cnt = 0

    for dir in A:
        if dir == EAST:
            cnt += 1
        else:
            answer += cnt
            
    if answer > 1000000000:
        return -1
        
    return answer
728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€