# Maximize the value of the given expression in C++

## Problem statement

Given three non-zero integers a, b and c. The task is to find the maximum value possible by putting addition and multiplication signs between them in any order.

Please note that rearrangement of integers is allowed but addition and multiplication sign must be used once.

If a = 1, b = 3 and c = 5 then maximum value will be 20 as follows−

(1 + 3) * 5 = 20

## Algorithm

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

## Example

Live Demo

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

## Output

When you compile and execute the above program. It generates the following output−

Maximum value = 20

Updated on: 24-Dec-2019

171 Views

##### Kickstart Your Career

Get certified by completing the course

Advertisements