끄적끄적

Codility Lesson5 - PassingCars 본문

Codility Lessons

Codility Lesson5 - PassingCars

kminx 2023. 9. 20. 11:42

Codility Lesson5 - PassingCars

https://app.codility.com/demo/results/training9CG426-3S9/

 

Test results - Codility

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

app.codility.com

 

문제

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.

Write an efficient algorithm for the following assumptions:

  • 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.

내가 이해한 문제

 

정답

def solution(A):

    pair=0


    for i in range(len(A)):
        if A[i]==0:
            for j in range(i,len(A)):
                if A[j]==1:
                    pair +=1



    if pair>1000000000:
        return -1
    else:
        return pair

 

결과

- 너무 오래 걸림. 시간 줄인 필요 있음. for문 안에 for 문은 런타임이 너무 길어서 방법 수정 필요


정답

def solution(A):

    pair=0
    p=0
    e_idx_list=[]

    for idx,value in enumerate(A):
        if value == 0:
            e_idx_list.append(idx)
    
    e_length=len(e_idx_list)

    if len(e_idx_list)==0:
        return 0
    else:
        for idx,value in enumerate(e_idx_list):
            p=len(A)-(e_length-idx)-(value)
            # 전체 개수에서 east로 가는 차량 개수 제거, 앞서 west로 출발한 차량과는 교차 불가능하니 제거
            pair+=p


    if pair>1000000000:
        return -1
    else:
        return pair

-> (e_length - idx) 대신   len(e_idx_list[i:])를 하니까  O(n**2)가 나와서  timeout이 떠서 저렇게 수정.

    전체 지나가는 차량의 수에서 이후에 동쪽으로 지나갈 차량의 수 제거, 그리고 본인 이전에 지나간 차량의 수 제거.
   

결과

'Codility Lessons' 카테고리의 다른 글

Codility Lesson5 - GenomicRangeQuery  (0) 2023.09.20
Codility Lesson5 - CountDiv  (0) 2023.09.20
Codility Lesson4 - MissingInteger  (0) 2023.09.19
Codility Lesson4 - MaxCounters  (0) 2023.09.18
Codility Lesson4 - PermCheck  (0) 2023.09.18