Minimize arithmetic operations to be performed on adjacent elements of given Array to reduce it
Last Updated :
23 Jul, 2025
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
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem