[백준] 14753번 MultiMax C++ 문제풀이

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';
}