Computer Science/알고리즘

[Codility] 6. Sorting

hyunjin 2023. 12. 17. 00:26

6.1 Distinct

Write a function that, given an array A consisting of N integers, returns the number of distinct values in array A.

 

N개의 정수로 구성된 배열 A가 주어지면 배열 A의 고유한 값의 수를 반환하는 함수를 작성합니다.

def solution(A):
    if len(A) == 0:
        return 0
    A.sort()
    cnt = 1
    for i in range(1, len(A)):
        if A[i] != A[i-1]:
            cnt+=1
    return cnt

 

6.2 MaxProductOfThree

A non-empty array A consisting of N integers is given. The product of triplet (P, Q, R) equates to A[P] * A[Q] * A[R] (0 ≤ P < Q < R < N).

Write a function that, given a non-empty array A, returns the value of the maximal product of any triplet.

 

N개의 정수로 구성된 비어 있지 않은 배열 A가 주어집니다. 삼중항 (P, Q, R)의 곱은 A[P] * A[Q] * A[R] (0 ≤ P < Q < R < N)과 같습니다.

비어 있지 않은 배열 A가 주어졌을 때, 임의의 삼중항의 최대 곱의 값을 반환하는 함수를 쓰시오.

 

def solution(A):
    A.sort()
    return max(A[-1] * A[0] * A[1], A[-1] * A[-2] * A[-3])

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

[Codility] 7. Stacks, Queues  (1) 2023.12.17
[Codility] 5. Prefix Sums  (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