Computer Science/알고리즘

[Codility] 5. Prefix Sums

hyunjin 2023. 12. 17. 00:19

5.1 PassingCars

A non-empty array A consisting of N integers is given. The consecutive elements of array A represent consecutive cars on a road.
Array A contains only 0s and/or 1s:
- 0 represents a car traveling east,
- 1 represents a car traveling west.

The goal is to count passing cars. We say that a pair of cars (P, Q), where 0 ≤ P < Q < N, is passing when P is traveling to the east and Q is traveling to the west.
Write a function that, given a non-empty array A of N integers, returns the number of pairs of passing cars.

 

N개의 정수로 이루어진 비어 있지 않은 배열 A가 주어집니다. 배열 A의 연속된 원소들은 도로 위의 연속된 자동차들을 나타냅니다.
A 배열에는 0 및/또는 1만 포함됩니다:
- 0은 동쪽으로 이동하는 차를 나타냅니다,
- 1은 서쪽으로 이동하는 차를 나타냅니다.

목표는 지나가는 차들을 세는 것입니다. 우리는 P가 동쪽으로, Q가 서쪽으로 이동할 때 0 ≤ P < Q < N인 한 쌍의 차(P, Q)가 지나간다고 말합니다.
N개의 정수로 이루어진 비어 있지 않은 배열 A가 주어지면 지나가는 자동차의 쌍수를 반환하는 함수를 쓰시오

def prefix_sums(A):
    n = len(A)
    P = [0] * (n + 1)
    for k in range(1, n + 1):
        P[k] = P[k - 1] + A[k - 1]
    return P

def solution(A):
    P = prefix_sums(A)
    cnt = 0
    for i, a in enumerate(A):
        if a == 0:
            cnt += (P[-1] - P[i])
        if cnt > 1000000000:
            return -1
    return cnt

'Computer Science > 알고리즘' 카테고리의 다른 글

[Codility] 7. Stacks, Queues  (1) 2023.12.17
[Codility] 6. Sorting  (1) 2023.12.17
[Codility] 4. Counting Elements  (1) 2023.12.17
[Codility] 3. Complexity  (1) 2023.12.16
[Codility] 2. Array  (1) 2023.12.16