본문 바로가기

Lesson 6. Sorting - MaxProductOfThree

반응형

1. 문제

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

 

세개의 수를 곱했을 때, 최대값을 구하는 문제

 

예) return 60

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

 

\( A[2] \times A[4] \times A[5] =  2 \times 5 \times 6 = 60 \)

 

2. 매개변수 조건

Vector A 크기: 3 ~ 100,000

Vector A 요소 값 범위: -1,000 ~ 1,000

 

3. 코드 (C++)

정렬 후, 최대값 3개를 곱하면 함정에 빠진것이다.

'음수 \( \times \) 음수 = 양수' 임을 생각해야한다.

#include <algorithm>

int solution(vector<int> &A) {
    
    sort(A.begin(), A.end());

    int last_idx = A.size() - 1;

    int max_value1 = A[0] * A[1] * A.back(); //최대값 후보1
    int max_value2 = A[last_idx] * A[last_idx - 1] * A[last_idx - 2]; // 최대값 후보2

    return (max_value1 > max_value2) ? max_value1 : max_value2;
}
반응형