[Codility] MaxProductOfThree

hamsteak·2023년 10월 7일
0

ps

목록 보기
26/39

배열 A에서 세 개의 원소를 골라 곱한 결과들 중 가장 큰 값을 구하는 문제.

원소값의 범위에 음수가 포함되어 있으므로 최대값을 구하기 위해서 두 가지 경우를 체크하면 된다.

  1. 절대값이 가장 큰 세 개의 양수
  2. 절대값이 가장 큰 두 개의 음수와 하나의 양수

https://app.codility.com/programmers/lessons/6-sorting/max_product_of_three/

cpp code

#include <algorithm>

int solution(vector<int> &A) {
    vector<int> P, N;
    for (int i : A) {
        if (i < 0) N.push_back(i);
        else P.push_back(i);
    }
    sort(P.begin(), P.end(), greater<int>());
    sort(N.begin(), N.end(), less<int>());

    int ans = A[0] * A[1] * A[2];
    if (P.size() >= 3) {
        ans = max(ans, P[0] * P[1] * P[2]);
    }
    if (N.size() >= 2 && P.size() >= 1) {
        ans = max(ans, N[0] * N[1] * P[0]);
    }
    return ans;
}
profile
안녕하세요

0개의 댓글