- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ code to find minimum arithmetic mean deviation
Suppose we have an array A with 3 elements. A[1] is arithmetic mean of two elements A[0] and A[3] if A[0] + A[2] = 2 * A[1]. Arithmetic mean deviation of three numbers d(A[0], A[1], A[2]) is |A[0] + A[2] - 2*A[1]|. 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[0] and increase A[1], 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[0] b := A[1] c := A[2] 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[0]; int b = A[1]; int c = A[2]; 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