
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).
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:
class Solution { public int solution(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].
주어진 N개의 정수로 구성된 비어 있지 않은 배열 A가 있습니다. 삼중항 (P, Q, R)의 곱은 A[P] A[Q] A[R] (0 ≤ P < Q < R < N)입니다.
예를 들어, 배열 A가 다음과 같을 때:
A[0] = -3 A[1] = 1 A[2] = 2 A[3] = -2 A[4] = 5 A[5] = 6 다음과 같은 예시 삼중항이 포함됩니다:
(0, 1, 2), 곱은 −3 1 2 = −6 (1, 2, 4), 곱은 1 2 5 = 10 (2, 4, 5), 곱은 2 5 6 = 60 당신의 목표는 어떤 삼중항의 최대 곱을 찾는 것입니다.
비어 있지 않은 배열 A가 주어졌을 때, 어떤 삼중항의 최대 곱의 값을 반환하는 함수를 작성하세요.
예를 들어, 배열 A가 다음과 같을 때:
A[0] = -3 A[1] = 1 A[2] = 2 A[3] = -2 A[4] = 5 A[5] = 6 함수는 삼중항 (2, 4, 5)의 곱이 최대이므로 60을 반환해야 합니다.
N은 [3…100,000] 범위 내의 정수입니다; 배열 A의 각 요소는 [−1,000…1,000] 범위 내의 정수입니다.
문제풀이
import java.util.Arrays;
class Solution {
public int solution(int[] A) {
Arrays.sort(A);
int n = A.length;
int maxProduct = Math.max(A[0] * A[1] * A[n-1], A[n-1] * A[n-2] * A[n-3]);
return maxProduct;
}
}
배열을 정렬한 후, 가장 작은 두 값과 가장 큰 값을 곱한 값과 가장 큰 세 값을 곱한 값 중 최대값을 반환합니다.
제출결과

문제풀어보기 -> https://app.codility.com/programmers/lessons/6-sorting/max_product_of_three/