Minimum number that can be obtained by applying ' + ' and ' * ' operations on array elements | Java program for the above approach ; Function to find the smallest number that can be obtained after applying the arithmetic operations mentioned in the String S ; Stores the count of multiplication operator in the String ; Store the required result ; Iterate in the range to create the mask ; Checking the number of bits that are set in the mask ; Check if the number of bits that are set in the mask is multiplication operation ; Storing the elements that is to be added ; Apply the multiplications operation first ; If sign is ' * ' , then multiply last element of deque with arr [ i ] ; Push last multiplied element in the deque ; If the element is to be added , then add it to the deque ; Add all the element of the deque ; Minimize the answer with the given sum ; Driver Code
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 ) ) ; } }