在 C++ 中最大化给定表达式的值


问题陈述

给出三个非零整数 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

更新于:2019-12-24

247 次浏览

开启您的 职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.