Given an array arr[] consisting of N positive integers and a string S of length (N – 1), containing characters ‘+’ and ‘*’, the task is to find the smallest number that can be obtained after applying the arithmetic operations mentioned in the string S on the array elements in any order.
Examples:
Input: A[] ={2, 2, 2, 2}, S = “**+”
Output: 8
Explanation:
Operation 1: Perform the multiplication operation on the first two elements operation i.e., arr[0]*arr[1] = 2*2 = 4. Now the array modifies to {4, 2, 2}.
Operation 2: Perform the multiplication operation on the remaining two elements i.e., arr[1]*arr[2] = 2*2 = 4. Now the array modifies to {4, 4}.
Operation 3: Perform the addition operation on the remaining elements arr[0] + arr[1] = 4 + 4 = 8. Now the array modifies to {8}.
Therefore, the result of the operation performed is 8, which is minimum.
Input: A[] = {1, 2, 3, 4}, S = “*++”
Output: 9
Approach: The given problem can be solved using bit-masking. Follow the steps below to solve the problem:
- Store the count of the multiplication and addition operation in the string S in variables, say mul and add respectively.
- Now, the operation applied on the elements of the array can be encoded in a mask(binary string) such that if the ith bit of mask is set then it is equal to ‘1’, and multiplication operation has to be performed. Otherwise, perform addition.
- Initialize a variable, say ans as INT_MAX that stores the minimum value of the result.
- So, create all masks in the range [0, 2(N – 1)] and find the number of set bits in the mask and perform the following steps:
- If the number of set bits in the mask is equal to mul, then apply this mask on the array A[] i.e., if the ith bit of mask is ‘1’ then perform multiplication operation on the ith element and (i + 1)th element.
- Otherwise, perform addition.
- Update the value of ans to the minimum of the ans and the calculated value in the above step.
- After completing the above steps, print the value of ans as the result.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minimumSum( int A[], int N, string S)
{
int mul = 0;
for ( int i = 0;
i < ( int )S.size(); i++) {
if (S[i] == '*' )
mul += 1;
}
int ans = 1000000;
for ( int i = 0;
i < (1 << (N - 1)); i++) {
int cnt = 0;
vector< char > v;
for ( int j = 0; j < N - 1; j++) {
if ((1 << j) & (i)) {
cnt += 1;
v.push_back( '*' );
}
else {
v.push_back( '+' );
}
}
if (cnt == mul) {
deque< int > d;
d.push_back(A[0]);
for ( int j = 0; j < N - 1; j++) {
if (v[j] == '*' ) {
int x = d.back();
d.pop_back();
x = x * A[j + 1];
d.push_back(x);
}
else {
d.push_back(A[j + 1]);
}
}
int sum = 0;
while (d.size() > 0) {
int x = d.front();
sum += x;
d.pop_front();
}
ans = min(ans, sum);
}
}
return ans;
}
int main()
{
int A[] = { 2, 2, 2, 2 };
string S = "**+" ;
int N = sizeof (A) / sizeof (A[0]);
cout << minimumSum(A, N, S);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int minimumSum( int A[], int N, String S)
{
int mul = 0 ;
for ( int i = 0 ;
i < ( int )S.length(); i++)
{
if (S.charAt(i) == '*' )
mul += 1 ;
}
int ans = 1000000 ;
for ( int i = 0 ;
i < ( 1 << (N - 1 )); i++)
{
int cnt = 0 ;
Vector<Character> v = new Vector<Character>();
for ( int j = 0 ; j < N - 1 ; j++)
{
if ((( 1 << j) & (i)) > 0 )
{
cnt += 1 ;
v.add( '*' );
}
else
{
v.add( '+' );
}
}
if (cnt == mul)
{
LinkedList<Integer> d = new LinkedList<Integer>();
d.add(A[ 0 ]);
for ( int j = 0 ; j < N - 1 ; j++)
{
if (v.get(j) == '*' )
{
int x = d.getLast();
d.removeLast();
x = x * A[j + 1 ];
d.add(x);
}
else
{
d.add(A[j + 1 ]);
}
}
int sum = 0 ;
while (d.size() > 0 )
{
int x = d.peek();
sum += x;
d.removeFirst();
}
ans = Math.min(ans, sum);
}
}
return ans;
}
public static void main(String[] args)
{
int A[] = { 2 , 2 , 2 , 2 };
String S = "**+" ;
int N = A.length;
System.out.print(minimumSum(A, N, S));
}
}
|
Python3
def minimumSum(A, N, S):
mul = 0
for i in range ( len (S)):
if (S[i] = = "*" ):
mul + = 1
ans = 1000000
for i in range ( 1 << (N - 1 )):
cnt = 0
v = []
for j in range (N - 1 ):
if (( 1 << j) & i):
cnt + = 1
v.append( "*" )
else :
v.append( "+" )
if (cnt = = mul):
d = []
d.append(A[ 0 ])
for j in range (N - 1 ):
if (v[j] = = "*" ):
x = d[ len (d) - 1 ]
d.pop()
x = x * A[j + 1 ]
d.append(x)
else :
d.append(A[j + 1 ])
sum = 0
while ( len (d) > 0 ):
x = d[ 0 ]
sum + = x
d.pop( 0 )
ans = min (ans, sum )
return ans
A = [ 2 , 2 , 2 , 2 ]
S = "**+"
N = len (A)
print (minimumSum(A, N, S))
|
C#
using System;
using System.Collections.Generic;
public class GFG{
static int minimumSum( int []A, int N, String S)
{
int mul = 0;
for ( int i = 0;
i < ( int )S.Length; i++)
{
if (S[i] == '*' )
mul += 1;
}
int ans = 1000000;
for ( int i = 0;
i < (1 << (N - 1)); i++)
{
int cnt = 0;
List< char > v = new List< char >();
for ( int j = 0; j < N - 1; j++)
{
if (((1 << j) & (i)) > 0)
{
cnt += 1;
v.Add( '*' );
}
else
{
v.Add( '+' );
}
}
if (cnt == mul)
{
List< int > d = new List< int >();
d.Add(A[0]);
for ( int j = 0; j < N - 1; j++)
{
if (v[j] == '*' )
{
int x = d[d.Count-1];
d.RemoveAt(d.Count-1);
x = x * A[j + 1];
d.Add(x);
}
else
{
d.Add(A[j + 1]);
}
}
int sum = 0;
while (d.Count > 0)
{
int x = d[0];
sum += x;
d.RemoveAt(0);
}
ans = Math.Min(ans, sum);
}
}
return ans;
}
public static void Main(String[] args)
{
int []A = { 2, 2, 2, 2 };
String S = "**+" ;
int N = A.Length;
Console.Write(minimumSum(A, N, S));
}
}
|
Javascript
<script>
function minimumSum(A, N, S)
{
let mul = 0;
for (let i = 0; i < S.length; i++)
{
if (S[i] == "*" )
mul += 1;
}
let ans = 1000000;
for (let i = 0; i < 1 << (N - 1); i++)
{
let cnt = 0;
let v = [];
for (let j = 0; j < N - 1; j++)
{
if ((1 << j) & i)
{
cnt += 1;
v.push( "*" );
} else
{
v.push( "+" );
}
}
if (cnt == mul)
{
let d = [];
d.push(A[0]);
for (let j = 0; j < N - 1; j++)
{
if (v[j] == "*" )
{
let x = d[d.length - 1];
d.pop();
x = x * A[j + 1];
d.push(x);
}
else
{
d.push(A[j + 1]);
}
}
let sum = 0;
while (d.length > 0)
{
let x = d[0];
sum += x;
d.shift();
}
ans = Math.min(ans, sum);
}
}
return ans;
}
let A = [ 2, 2, 2, 2 ];
let S = "**+" ;
let N = A.length;
document.write(minimumSum(A, N, S));
</script>
|
Time Complexity: O(2(N – 1)*N)
Auxiliary Space: O(N)