Wednesday, 27 Oct 2021

# Generate a sequence such that float division of array elements is maximized

Given an array arr[] consisting of N integers, the task is to find the expression by using parenthesis ‘(‘ and ‘)’ and division operator ‘/’ to maximize the value of the expression of subsequent float division of array elements.
Examples:

Input: arr[] = {1000, 100, 10, 2}Output: “1000/(100/10/2)”Explanation:The value of the expression 1000/(100/10/2) can be calculated as 1000/((100/10)/2) = 200.
Input: arr[] = {2, 3, 4}Output: “2/(3/4)”

Approach: The idea is based on the observation that for every division, the result is maximum only when the denominator is minimum. Therefore, the task reduces to place the parentheses and operators in such a way that the denominator is minimum. Consider the following example to solve the problem:
Consider an expression 1000 / 100 / 10 / 2.To make its value maximum, denominator needs to be minimized. Therefore, the denominators need to be in the sequence 100, 10, 2.Now, consider the following cases:
100 / (10 / 2) = (100 × 2) / 10 = 20
(100 / 10) / 2 = 10 / 2 = 5
Therefore, the minimized value for the expression is obtained for the second case. Therefore, 1000 / (100 / 10 / 2) is the required sequence.

Therefore, from the above example, it can be concluded that the parenthesis needs to be placed to the sequence after the first integer that makes the whole sequence from the second integer reduced to the minimum value possible.Follow the steps below to solve the problem:
Initialize a string S as “”, to store the final expression.
If N is equal to 1, print the integer in string form.
Otherwise, append arr and “/(“ in S, and then append all the remaining integers of arr[] separated by “/”.
At last, append “)” in the string S and print the string S as the result.
Below is the implementation of the above approach:

C++14

#include
using namespace std;

void generateSequence(int arr[], int n)
{

string ans;

ans = to_string(arr);

if (n == 1)
cout