문제
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].
풀이
벡터의 원소 중 세 개를 무작위로 골라서 세 개의 곱이 가장 클 때의 값을 구하는 문제이다.
양수만 있는 벡터의 경우엔 가장 큰 세 숫자를 곱하면 되지만, 음수가 있을 때는 달라진다.
먼저, 내림차순으로 벡터를 정렬한다. 내림차순으로 정렬을 하게 되면 양 끝으로 갈 수록 절댓값이 커지게 된다.
정렬을 한 뒤 가장 큰 세가지 수를 기준으로 보게 되면,
- 음수가 세 개 : 아무리 곱해도 음수가 나오므로, 큰 수 세 가지를 곱하면 정답
- 음수가 두 개 : 양수 하나와 절댓값이 큰 음수 두 개를 곱하는게 가장 큼
- 음수가 한 개 : 똑같이 양수 하나와 절댓값이 큰 음수 두 개를 곱하는게 가장 큼
- 음수가 없음 : 가장 큰 양수를 포함하여 나머지 두 양수의 곱 또는 절댓값이 두 음수의 곱 중 큰 것이 정답
위의 기준을 통하여 코딩을 하면 된다.
코드
#include <algorithm>
int solution(vector<int> &A) {
sort(A.begin(), A.end(), greater<int>());
int minusCount = 0;
for (int i = 0; i < 3; i++) {
if (A[i] < 0)
minusCount++;
}
int size = A.size();
if (minusCount == 3)
return A[0] * A[1] * A[2];
else if (minusCount == 2) {
return A[0] * A[size - 1] * A[size - 2];
}
else if (minusCount == 1) {
return A[0] * A[size - 1] * A[size - 2];
}
else {
if (A[1] * A[2] > A[size - 1] * A[size - 2])
return A[0] * A[1] * A[2];
else
return A[0] * A[size - 1] * A[size - 2];
}
}
'Old > Codility' 카테고리의 다른 글
Codility - Distinct // C++ (0) | 2020.02.19 |
---|---|
Codility - Count Div // C++ (0) | 2020.02.19 |
Codility - Genomic Range Query // C++ (0) | 2020.02.18 |
Codility - Passing Cars // C++ (0) | 2020.02.06 |
Codility - Max Counters // C++ (0) | 2020.02.06 |