문제 설명
0이 아닌 세 개의 정수 a, b, c가 주어집니다. 작업은 순서에 관계없이 덧셈과 곱셈 기호를 넣어 가능한 최대값을 찾는 것입니다.
정수의 재배열은 허용되지만 덧셈과 곱셈 기호는 한 번만 사용해야 합니다.
a =1, b =3, c =5이면 최대값은 다음과 같이 20이 됩니다.
(1 + 3) * 5 = 20
알고리즘
1. If all numbers are positive, then add two small numbers and multiply result with larger one 2. If only two numbers are positive, then multiply 2 positive numbers and add remaining number 3. If only one number is positive, then multiply 2 negative number and add remaining number 4. If all numbers are negative, then add two largest integers and multiply then with remaining number
예시
#include <bits/stdc++.h>
using namespace std;
int getMaximumResult(int a, int b, int c){
int negativeCnt = 0;
int sum = a + b + c;
int mul = a * b * c;
int largest = max(a, max(b, c));
int smallest = min(a, min(b, c));
if (a < 0) {
++negativeCnt;
}
if (b < 0) {
++negativeCnt;
}
if (c < 0) {
++negativeCnt;
}
if (negativeCnt == 0) {
return (sum - largest) * largest;
}
else if (negativeCnt == 1) {
return (mul / smallest) + smallest;
}
else if (negativeCnt == 2) {
return (mul / largest) + largest;
}
else if (negativeCnt == 3) {
return (sum - smallest) * smallest;
}
}
int main(){
int a = 1, b = 3, c = 5;
cout << "Maximum value = " << getMaximumResult(a, b, c) << endl;
return 0;
} 출력
위의 프로그램을 컴파일하고 실행할 때. 다음 출력을 생성합니다-
Maximum value = 20