VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-number-that-can-be-obtained-by-applying-and-operations-on-array-elements/

⇱ Minimum number that can be obtained by applying '+' and '*' operations on array elements - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum number that can be obtained by applying '+' and '*' operations on array elements

Last Updated : 23 Jul, 2025

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:


Output: 
8

 

Time Complexity: O(2(N - 1)*N)
Auxiliary Space: O(N)

Comment