Optimal Division in C++


Suppose we have a list of positive integers; the adjacent integers will perform the float division. So for example, [2,3,4] -> 2 / 3 / 4. Now, we can add any number of parenthesis at any position to change the priority of these operations. We should find out how to add parenthesis to get the maximum result, we have to find the corresponding expression in string format. Our expression should NOT contain redundant parenthesis. So if the input is like [1000,100,10,2], then the result will be “1000/(100/10/2)”.

To solve this, we will follow these steps −

  • n := size of nums array
  • if n is 0 then return a blank string.
  • num := nums[0] as string
  • if n is 1, then return num
  • if n is 2, then return num concatenate /, concatenate nums[1] as string
  • den := an empty string
  • for i in range 1 to n – 1
    • den := den + nums[i] as string
    • if i is not n – 1, then den := den concatenate ‘/’
  • return num concatenate / concatenate ( concatenate den , concatenate )

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   string optimalDivision(vector<int>& nums) {
      int n = nums.size();
      if(n == 0) return "";
      string num = to_string(nums[0]);
      if(n == 1) return num;
      if(n == 2) return num + "/" + to_string(nums[1]);
      string den = "";
      for(int i = 1; i < n; i++){
         den += to_string(nums[i]);
         if(i != n - 1) den += "/";
      }
      return num + "/" + "(" + den + ")";
   }
};
main(){
   vector<int> v = {1000,100,10,2};
   Solution ob;
   cout << (ob.optimalDivision(v));
}

Input

[1000,100,10,2]

Output

1000/(100/10/2)

Updated on: 04-May-2020

193 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements