# C++ code to find minimum arithmetic mean deviation

Suppose we have an array A with 3 elements. A is arithmetic mean of two elements A and A if A + A = 2 * A. Arithmetic mean deviation of three numbers d(A, A, A) is |A + A - 2*A|. We can perform following operations any number of times: Select two index i and j from the indices {0, 1, 2} such that i != j, then increase A[i] by 1 and decrease A[j] by 1. We have to find the minimum value of arithmetic mean deviation.

So, if the input is like A = [2, 2, 6], then the output will be 1, because if we decrease A and increase A, then array will be [1, 3, 6], so the mean deviation will be |1 + 6 - 2 * 3| = 1.

## Steps

To solve this, we will follow these steps −

a := A
b := A
c := A
return minimum of 1 and (((a + c - 2 * b) mod 3 + 3) mod 3)

## Example

Let us see the following implementation to get better understanding−

#include <bits/stdc++.h>
using namespace std;
int solve(vector<int> A){
int a = A;
int b = A;
int c = A;
return min(1, ((a + c - 2 * b) % 3 + 3) % 3);
}
int main(){
vector<int> A = { 2, 2, 6 };
cout << solve(A) << endl;
}

## Input

{ 2, 2, 6 }

## Output

1

Updated on: 11-Mar-2022

135 Views 