

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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)
- Related Questions & Answers
- Optimal Account Balancing in C++
- Division Operator in C#
- C++ Program for Optimal Page Replacement Algorithm
- DFA based division in C++?
- Optimal Binary Search Tree
- Set Optimal MySQL configuration in my.cnf?
- Optimal Lopsided Trees in Data Structure
- C++ Program to Perform Optimal Paranthesization Using Dynamic Programming
- Optimal Binary Search Trees in Data Structures
- Restoring Division Algorithm For Unsigned Integer in C++
- Division Operators in Python?
- Division Operators in Java
- Tuple Division in Python
- DFA based division
- Frequency Division Multiplexing
Advertisements