https://www.acmicpc.net/problem/14753
14753번: MultiMax
There are n cards, each with an integer on it where two or more cards can have the same integer. From these cards, we want to select two or three cards such that the product of numbers on the selected cards is maximum. For example, assume that there are 6
www.acmicpc.net
문제 풀이
이 문제는 결국 숫자들 중에서 2개 or 3개의 카드를 뽑아 만들수 있는 숫자들 중 최대 숫자를 출력하는 문제였다.
2개 뽑았을 때 최대가 되려면 (+값 중 제일 큰값) * (+값 중 2번째로 큰 값) 또는 (-값 중 제일 큰 값) * (-값 중 2번째로 큰값)
3개 뽑았을 때는 (+값 중 제일 큰값) * (+값 중 2번째로 큰 값) * (+값 중 3번째로 큰 값) 또는 (-값 중 제일 큰 값) * (-값 중 2번째로 큰값) * ( +값 중 제일 큰 값)
이 값들 중에 최대가 나오므로 계산해서 간단히 비교했다.
소스 코드
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
vector<int> num;
bool compare(int a, int b) {
return a > b;
}
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
int a;
cin >> a;
num.push_back(a);
}
sort(num.begin(), num.end(),compare);
int minus2 = num[n - 1] * num[n - 2];
int minus3 = num[n - 1] * num[n - 2] * num[0];
int minus_max = max(minus2, minus3);
int plus2 = num[0] * num[1];
int plus3 = num[0] * num[1] * num[2];
int plus_max = max(plus2, plus3);
int max_num = max(minus_max, plus_max);
cout << max_num << '\n';
}
'알고리즘' 카테고리의 다른 글
[백준] 14746번 Closest Pair C++ 문제풀이 (0) | 2023.10.18 |
---|---|
[백준] 14754번 Pizza Boxes C++ 문제풀이 (1) | 2023.10.16 |
[백준] 17626번 Four Squares C++ 문제풀이 (2) | 2023.10.13 |
[백준] 17521번 Byte Coin C++ 문제풀이 (1) | 2023.10.13 |
[백준] 16283번 FARM C++ 문제풀이 (1) | 2023.10.12 |