Open In App

Minimize arithmetic operations to be performed on adjacent elements of given Array to reduce it

Last Updated : 17 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[], the task is to perform arithmetic operations (+, -, *, /) on arr[] in sequence. These operations are performed on adjacent elements until array size reduces to 1. Finally, return the reduced value and number of operations required for the same. Refer to examples for more clarity. 

Examples:

Input: arr = {12, 10, 2, 9, 1, 2}
Output: Reduced Value: 10
Operations Performed:
+ : 2
– : 1
* : 1
/ : 1

Explanation:
Step 1: perform addition of consecutive element [22, 12, 11, 10, 3]
Step 2: perform subtraction of consecutive element [10, 1, 1, 7]
Step 3: perform multiplication of consecutive element[10, 1, 7]
Step 4: perform division of consecutive element [10, 0]
Step 5: Again perform addition of consecutive element[10]
 

Input: arr = {5, -2, -1, 2, 4, 5}
Output: Reduced Value: -3
Operations Performed:
+ : 2
– : 2
* : 1
/ : 1

Approach: Since in this problem we have to perform operations based on the sequence like first addition then subtraction, then multiplication and then division hence we can use Switch case to solve this problem.

Initialize an dictionary where operator (+, -, *, /) as key and 0 as value.  Using functions add, sub, mul and div, operation on array will be performed. It has as function Operation which maps the array with functions based on the value of c%4 and return the reduced array. where c keeps track of number of operations performed. Dictionary keeps track of each operations performed till size of array get reduced to 1.
Follow the steps below to solve given problem.

Step 1: Assign c to 1 and declare dictionary d.
 

  • Step 2: if c%4==1 then perform addition operation on consecutive element using Operation function.
     
  • Step 3: if c%4==2 then perform subtraction operation on consecutive element using Operation function.
     
  • Step 4: if c%4==3 then perform multiplication operation on consecutive element using Operation function.
     
  • Step 5: if c%4==0 then perform division operation on consecutive element using Operation function.
     
  • Step 6: step 2 will be repeated till size of array become equal to 1.
     
  • Step 7: d is used to keep track of each operation performed.

Below is the implementation of the above approach:

C++




// C++ program to implement the approach
#include <cmath>
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
 
// Function for adding consecutive elements
vector<int> add(vector<int> a)
{
  vector<int> res;
  for (int i = 0; i < a.size() - 1; i++) {
    res.push_back(a[i] + a[i + 1]);
  }
  return res;
}
 
// Function for subtracting consecutive elements
vector<int> sub(vector<int> a)
{
  vector<int> res;
  for (int i = 0; i < a.size() - 1; i++) {
    res.push_back(a[i] - a[i + 1]);
  }
  return res;
}
 
// Function for multiplying consecutive elements
vector<int> mul(vector<int> a)
{
  vector<int> res;
  for (int i = 0; i < a.size() - 1; i++) {
    res.push_back(a[i] * a[i + 1]);
  }
  return res;
}
 
// Function for dividing consecutive elements
vector<int> div(vector<int> a)
{
  vector<int> res;
  for (int i = 0; i < a.size() - 1; i++) {
    res.push_back((a[i] == 0 || a[i + 1] == 0)
                  ? 0
                  : floor(a[i] / a[i + 1]));
  }
  return res;
}
 
// Operation function which maps array
// to corresponding function based on value of i.
vector<int> Operation(int i, vector<int> A)
{
  switch (i) {
    case 1:
      return add(A);
    case 2:
      return sub(A);
    case 3:
      return mul(A);
    case 0:
      return div(A);
    default:
      return vector<int>();
  }
}
 
int main()
{
  // Keep track of number of operations of each operator
  unordered_map<char, int> d;
  d['/'] = 0;
  d['*'] = 0;
  d['-'] = 0;
  d['+'] = 0;
 
  vector<int> arr = { 5, -2, -1, 2, 1, 4, 5 };
  int c = 1;
 
  // Loop until size of array becomes equal to 1
  while (arr.size() != 1) {
    int x = c % 4;
    switch (x) {
      case 1:
        d['+']++;
        arr = Operation(x, arr);
        break;
      case 2:
        d['-']++;
        arr = Operation(x, arr);
        break;
      case 3:
        d['*']++;
        arr = Operation(x, arr);
        break;
      case 0:
        d['/']++;
        arr = Operation(x, arr);
        break;
    }
    c++;
  }
 
  // Printing reduced value
  cout << "Reduced value: " << arr[0] << endl;
 
  // Printing value of each operation performed to reduce
  // performed to reduce size of array to 1.
  cout << "Operations Performed:\n";
  for (auto i : d) {
    cout << i.first << ": " << i.second << endl;
  }
}
 
// This code is contributed by phasing17


Java




import java.util.*;
 
public class Main {
 
  // Function for adding consecutive elements
  public static ArrayList<Integer> add(ArrayList<Integer> a) {
    ArrayList<Integer> res = new ArrayList<Integer>();
    for (int i = 0; i < a.size() - 1; i++) {
      res.add(a.get(i) + a.get(i + 1));
    }
    return res;
  }
 
  // Function for subtracting consecutive elements
  public static ArrayList<Integer> sub(ArrayList<Integer> a) {
    ArrayList<Integer> res = new ArrayList<Integer>();
    for (int i = 0; i < a.size() - 1; i++) {
      res.add(a.get(i) - a.get(i + 1));
    }
    return res;
  }
 
  // Function for multiplying consecutive elements
  public static ArrayList<Integer> mul(ArrayList<Integer> a) {
    ArrayList<Integer> res = new ArrayList<Integer>();
    for (int i = 0; i < a.size() - 1; i++) {
      res.add(a.get(i) * a.get(i + 1));
    }
    return res;
  }
 
  // Function for dividing consecutive elements
  public static ArrayList<Integer> div(ArrayList<Integer> a) {
    ArrayList<Integer> res = new ArrayList<Integer>();
    for (int i = 0; i < a.size() - 1; i++) {
      res.add((a.get(i) == 0 || a.get(i + 1) == 0)
              ? 0
              : (int) Math.floor(a.get(i) / a.get(i + 1)));
    }
    return res;
  }
 
  // Operation function which maps array
  // to corresponding function based on value of i.
  public static ArrayList<Integer> Operation(int i, ArrayList<Integer> A) {
    switch (i) {
      case 1:
        return add(A);
      case 2:
        return sub(A);
      case 3:
        return mul(A);
      case 0:
        return div(A);
      default:
        return new ArrayList<Integer>();
    }
  }
 
  public static void main(String[] args)
  {
 
    // Keep track of number of operations of each operator
    HashMap<Character, Integer> d = new HashMap<Character, Integer>();
    d.put('/', 0);
    d.put('*', 0);
    d.put('-', 0);
    d.put('+', 0);
 
    ArrayList<Integer> arr = new ArrayList<Integer>();
    arr.add(5);
    arr.add(-2);
    arr.add(-1);
    arr.add(2);
    arr.add(1);
    arr.add(4);
    arr.add(5);
 
    int c = 1;
 
    // Loop until size of array becomes equal to 1
    while (arr.size() != 1) {
      int x = c % 4;
      switch (x) {
        case 1:
          d.put('+', d.get('+') + 1);
          arr = Operation(x, arr);
          break;
        case 2:
          d.put('-', d.get('-') + 1);
          arr = Operation(x, arr);
          break;
        case 3:
          d.put('*', d.get('*') + 1);
          arr = Operation(x, arr);
          break;
        case 0:
          d.put('/', d.get('/') + 1);
          arr = Operation(x, arr);
          break;
      }
      c++;
    }
 
    // Printing reduced value
    System.out.println("Reduced value: " + arr.get(0));
 
    // Printing value of each operation performed to reduce
    // performed to reduce size of array to 1.
    System.out.println("Operations Performed:");
 
    // Printing value of each operation performed to reduce
    for (Map.Entry<Character, Integer> entry : d.entrySet()) {
      System.out.println(entry.getKey() + ": " + entry.getValue());
    }
  }}


Python3




# Function for adding consecutive element
def add(a):
    return [a[i]+a[i + 1] for i in range(len(a)-1)]
 
# Function for subtracting consecutive element
def sub(a):
    return [a[i] - a[i + 1] for i in range(len(a)- 1)]
 
# Function for multiplication of consecutive element
def mul(a):
    return [a[i] * a[i + 1] for i in range(len(a) - 1)]
 
# Function for division of consecutive element
def div(a):
    return [0 if a[i] == 0 or a[i + 1] == 0 \
            else a[i]//a[i + 1] \
                 for i in range(len(a) - 1)]
 
# Operation function which maps array
# to corresponding function
# based on value of i.
def Operation(i, A):
    switcher = {
        1: add,
        2: sub,
        3: mul,
        0: div
    }
    func = switcher.get(i, lambda: 'Invalid')
    return func(A)
  
# Driver Code
c = 1
 
# dictionary value which keep track
# of no of operation of each operator.
d = {'+':0, '-':0, '*':0, '/':0 }
 
arr =[5, -2, -1, 2, 1, 4, 5]
 
# loop till size of array become equal to 1.
while len(arr)!= 1:
    x = c % 4
    # After each operation value
    # in dictionary value is incremented
    # also reduced array
    # is assigned to original array.
    if x == 1:
        d['+'] += 1
        arr = Operation(x, arr)
    elif x == 2:
        d['-'] += 1
        arr = Operation(x, arr)
    elif x == 3:
        d['*'] += 1
        arr = Operation(x, arr)
    elif x == 0:
        d['/'] += 1
        arr = Operation(x, arr)
    c += 1
 
# Printing reduced value
print("Reduced value:", *arr)
 
 
# Printing value of each operation
# performed to reduce size of array to 1.
print("Operations Performed:")
for i in d.keys():
    print(str(i) + " : " +str(d[i]))


C#




using System;
using System.Linq;
using System.Collections.Generic;
 
class GFG {
 
    // Function for adding consecutive elements
    public static List<int> add(List<int> a)
    {
        List<int> res = new List<int>();
        for (int i = 0; i < a.Count - 1; i++) {
            res.Add(a[i] + a[i + 1]);
        }
        return res;
    }
 
    // Function for subtracting consecutive elements
    public static List<int> sub(List<int> a)
    {
        List<int> res = new List<int>();
        for (int i = 0; i < a.Count - 1; i++) {
            res.Add(a[i] - a[i + 1]);
        }
        return res;
    }
 
    // Function for multiplying consecutive elements
    public static List<int> mul(List<int> a)
    {
        List<int> res = new List<int>();
        for (int i = 0; i < a.Count - 1; i++) {
            res.Add(a[i] * a[i + 1]);
        }
        return res;
    }
 
    // Function for dividing consecutive elements
    public static List<int> div(List<int> a)
    {
        List<int> res = new List<int>();
        for (int i = 0; i < a.Count - 1; i++) {
            res.Add((a[i] == 0 || a[i + 1] == 0)
                        ? 0
                        : (int)Math.Floor((double)a[i]
                                          / a[i + 1]));
        }
        return res;
    }
 
    // Operation function which maps array
    // to corresponding function based on value of i.
    public static List<int> Operation(int i, List<int> A)
    {
        switch (i) {
        case 1:
            return add(A);
        case 2:
            return sub(A);
        case 3:
            return mul(A);
        case 0:
            return div(A);
        default:
            return new List<int>();
        }
    }
 
    public static void Main()
    {
        // Keep track of number of operations of each
        // operator
        Dictionary<char, int> d
            = new Dictionary<char, int>();
        d.Add('/', 0);
        d.Add('*', 0);
        d.Add('-', 0);
        d.Add('+', 0);
 
        List<int> arr = new List<int>();
        arr.Add(5);
        arr.Add(-2);
        arr.Add(-1);
        arr.Add(2);
        arr.Add(1);
        arr.Add(4);
        arr.Add(5);
 
        int c = 1;
 
        // Loop until size of array becomes equal to 1
        while (arr.Count != 1) {
            int x = c % 4;
            switch (x) {
            case 1:
                d['+']++;
                arr = Operation(x, arr);
                break;
            case 2:
                d['-']++;
                arr = Operation(x, arr);
                break;
            case 3:
                d['*']++;
                arr = Operation(x, arr);
                break;
            case 0:
                d['/']++;
                arr = Operation(x, arr);
                break;
            }
            c++;
        }
 
        // Printing reduced value
        Console.WriteLine("Reduced value: " + arr[0]);
 
        // Printing value of each operation performed to
        // reduce performed to reduce size of array to 1.
        Console.WriteLine("Operations Performed:");
 
        // Printing value of each operation performed to
        // reduce
        foreach(KeyValuePair<char, int> entry in d
                    .OrderBy(a => -a.Value)
                    .ThenBy(b => b.Key))
        {
            Console.WriteLine(entry.Key + ": "
                              + entry.Value);
        }
    }
}
 
// This code is contributed by phasing17


Javascript




// JS program to implement the approach
 
// Function for adding consecutive element
function add(a) {
    return a.slice(0, a.length - 1).map((val, i) => val + a[i + 1]);
}
 
// Function for subtracting consecutive element
function sub(a) {
    return a.slice(0, a.length - 1).map((val, i) => val - a[i + 1]);
}
 
// Function for multiplication of consecutive element
function mul(a) {
    return a.slice(0, a.length - 1).map((val, i) => val * a[i + 1]);
}
 
// Function for division of consecutive element
function div(a) {
    return a.slice(0, a.length - 1).map((val, i) => (val === 0 || a[i + 1] === 0) ? 0 : Math.floor(val / a[i + 1]));
}
 
// Operation function which maps array
// to corresponding function
// based on value of i.
function Operation(i, A) {
    switch (i) {
        case 1: return add(A);
        case 2: return sub(A);
        case 3: return mul(A);
        case 0: return div(A);
        default: return 'Invalid';
    }
}
 
// Driver Code
let c = 1;
 
// Object which keep track
// of no of operation of each operator.
let d = { '+': 0, '-': 0, '*': 0, '/': 0 };
 
let arr = [5, -2, -1, 2, 1, 4, 5];
 
// loop till size of array become equal to 1.
while (arr.length !== 1) {
    let x = c % 4;
    // After each operation value
    // in object value is incremented
    // also reduced array
    // is assigned to original array.
    switch (x) {
        case 1:
            d['+']++;
            arr = Operation(x, arr);
            break;
        case 2:
            d['-']++;
            arr = Operation(x, arr);
            break;
        case 3:
            d['*']++;
            arr = Operation(x, arr);
            break;
        case 0:
            d['/']++;
            arr = Operation(x, arr);
            break;
    }
    c++;
}
 
// Printing reduced value
console.log("Reduced value:", ...arr);
 
// Printing value of each operation
// performed to reduce size of array to 1.
console.log("Operations Performed:");
for (let i in d) {
    console.log(`${i} : ${d[i]}`);
}
 
// This code is contributed by phasing17


Output

Reduced value: -3
Operations Performed:
+ : 2
- : 2
* : 1
/ : 1

Time Complexity: O(N)
Auxiliary Space: O(N)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads