PassingCars

HeeSeong·2021년 6월 10일

Codility

목록 보기
11/34
post-thumbnail

🔗 문제 링크

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


❔ 문제 설명


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.

For example, consider array A such that:

A[0] = 0
A[1] = 1
A[2] = 0
A[3] = 1
A[4] = 1

We have five pairs of passing cars: (0, 1), (0, 3), (0, 4), (2, 3), (2, 4).

Write a function:

def solution(A)

that, given a non-empty array A of N integers, returns the number of pairs of passing cars.

The function should return −1 if the number of pairs of passing cars exceeds 1,000,000,000.

For example, given:

A[0] = 0
A[1] = 1
A[2] = 0
A[3] = 1
A[4] = 1

the function should return 5, as explained above.


⚠️ 제한사항


  • N is an integer within the range [1..100,000];

  • each element of array A is an integer that can have one of the following values: 0, 1.



💡 풀이 (언어 : Java)


P의 개수를 카운트하고 Q가 나올때마다 앞의 P의 개수만큼 정답에 카운트해주는 알고리즘이다. 정답의 범위가 int의 최대 범위보다 높게 나오는 것이 가능하고, 이러면 오버플로우가 발생해 음수가 나오기 때문에 변수를 long으로 선언해주었다.

class Solution {
    public int solution(int[] A) {
        // 동쪽으로 가는 차 P의 누적 개수
        int p = 0;
        // (P,Q) 쌍의 개수, int의 범위를 넘는게 가능해서 long
        long answer = 0;
        for (int n : A) {
            // 동쪽으로 가는 차 P가 등장하면 카운트
            if (n == 0)
                p++;
            // 앞에 나왔던 차 P의 개수만큼 카운트
            else
                answer += p;
        }
        // 10억 보다 클경우 -1
        return (answer > 1000000000) ? -1 : (int) answer;
    }
}
profile
끊임없이 성장하고 싶은 개발자

0개의 댓글