Minimize arithmetic operations to be performed on adjacent elements of given Array to reduce it
Last Updated :
17 Feb, 2023
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
OutputReduced value: -3
Operations Performed:
+ : 2
- : 2
* : 1
/ : 1
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Minimize Cost to reduce the Array to a single element by given operations
Given an array a[] consisting of N integers and an integer K, the task is to find the minimum cost to reduce the given array to a single element by choosing any pair of consecutive array elements and replace them by (a[i] + a[i+1]) for a cost K * (a[i] + a[i+1]). Examples: Input: a[] = {1, 2, 3}, K
15+ min read
Minimize increment-decrement operation on adjacent elements to convert Array A to B
Given two arrays A[] and B[] consisting of N positive integers, the task is to find the minimum number of increment and decrements of adjacent array elements of the array A[] required to convert it to the array B[]. If it is not possible, then print "-1". Examples: Input: A[] = {1, 2}, B[] = {2, 1}O
11 min read
Minimize the non-zero elements in the Array by given operation
Given an array arr[] of length N, the task is to minimize the count of the number of non-zero elements by adding the value of the current element to any of its adjacent element and subtracting from the current element at most once.Examples: Input: arr[] = { 1, 0, 1, 0, 0, 1 } Output: 2 Explanation:
5 min read
Minimum possible sum of array elements after performing the given operation
Given an array arr[] of size N and a number X. If any sub array of the array(possibly empty) arr[i], arr[i+1], ... can be replaced with arr[i]/x, arr[i+1]/x, .... The task is to find the minimum possible sum of the array which can be obtained. Note: The given operation can only be performed once.Exa
9 min read
Reduce all array elements to zero by performing given operations thrice
Given an array arr[] of size N, the task is to convert every array element to 0 by applying the following operations exactly three times: Select a subarray.Increment every element of the subarray by the integer multiple of its length. Finally, print the first and last indices of the subarray involve
9 min read
Minimum operations required to modify the array such that parity of adjacent elements is different
Given an array A[], the task is to find the minimum number of operations required to convert the array into B[] such that for every index in B (except the last) parity(b[i]) != parity(b[i + 1]) where parity(x) = x % 3. Below is the operation to be performed: Any element from the set {1, 2} can be ad
9 min read
Minimize sum of Array formed using given relation between adjacent elements
Given a binary string S of length N, consisting of 0's and 1's, the task is to find the minimum sum of the array of non-negative integers of length N+1 created by following the below conditions: If the ith number in the given binary string is 0, then the (i + 1)th number in the array must be less th
11 min read
Minimize operations of removing 2i -1 array elements to empty given array
Given an array arr[] of size N, the task is to empty given array by removing 2i - 1 array elements in each operation (i is any positive integer). Find the minimum number of operations required. Examples: Input: arr[] = { 2, 3, 4 } Output: 1 Explanation: Removing (22 - 1) elements i.e { arr[0], arr[1
5 min read
Minimum number of given operations required to reduce the array to 0 element
Given an array arr[] of N integers. The task is to find the minimum number of given operations required to reduce the array to 0 elements. In a single operation, any element can be chosen from the array and all of its multiples get removed including itself.Examples: Input: arr[] = {2, 4, 6, 3, 4, 6,
6 min read
Minimum count of elements required to obtain the given Array by repeated mirror operations
Given an array arr[] consisting of N integers, the task is to find the array K[] of minimum possible length such that after performing multiple mirror operations on K[], the given array arr[] can be obtained. Mirror Operation: Appending all the array elements to the original array in reverse order.
7 min read