본문 바로가기
SW/알고리즘 문제풀이

[Codility] Lesson6 - Sorting: Max Product of Three

by 미래미래로 2020. 12. 23.
728x90

Problem

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

For example, array A such that:

A[0] = -3 A[1] = 1 A[2] = 2 A[3] = -2 A[4] = 5 A[5] = 6

contains the following example triplets:

  • (0, 1, 2), product is −3 * 1 * 2 = −6
  • (1, 2, 4), product is 1 * 2 * 5 = 10
  • (2, 4, 5), product is 2 * 5 * 6 = 60

Your goal is to find the maximal product of any triplet.

Write a function:

int solution(vector<int> &A);

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

For example, given array A such that:

A[0] = -3 A[1] = 1 A[2] = 2 A[3] = -2 A[4] = 5 A[5] = 6

the function should return 60, as the product of triplet (2, 4, 5) is maximal.

Write an efficient algorithm for the following assumptions:

  • N is an integer within the range [3..100,000];
  • each element of array A is an integer within the range [−1,000..1,000].

    Copyright 2009–2020 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

How to solve

- 정보

N의 길이를 가진 벡터 A

 

- 구해야 하는것?

A 벡터중 3개 원소의 곱이 가장 큰 수

 

- 풀이

3원소의 곱이 가장 크려면, 

A를 오름차순으로 정렬하고

1) 마지막 3개 곱, A[N-1]*A[N-2]*A[N-3]

2) A[0], A[1] 이 음수이고, A[N-1]이 양수인 경우 A[0]*A[1]*A[N-1]

1)과 2)를 비교해 큰 값을 return 하면 된다.

Solution(c++)

// you can use includes, for example:
#include <bits/stdc++.h>

// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;

int solution(vector<int> &A) {
    // write your code in C++14 (g++ 6.2.0)
    int len = A.size();
    sort(A.begin(), A.end());
    int right_triplet = A[len-1]*A[len-2]*A[len-3];
    
    if(A[0]<0 && A[1]<0 && A[len-1]>0){
        if(right_triplet < A[0]*A[1]*A[len-1]){
            right_triplet = A[0]*A[1]*A[len-1];
        }
    }
    return right_triplet;
}

Test Result

app.codility.com/demo/results/training27Q8HU-9RF/

 

Test results - Codility

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). For example, array A such that: A[0] = -3 A[1] = 1 A[2] = 2 A[3] = -2 A[4] = 5 A[5] = 6 contains the following exam

app.codility.com

 

728x90

댓글