coinPiles
#include <iostream>
using namespace std;
int minMoves(int a[], int n) {
int moves = 0, sum = 0;
for (int i = 0; i < n; i++) {
sum += a[i];
}
int avg = sum / n;
for (int i = 0; i < n; i++) {
if (a[i] > avg) {
moves += (a[i] - avg);
}
}
return moves;
}
int main() {
int n;
cout << "Enter the number of piles: ";
cin >> n;
int piles[n];
cout << "Enter the number of coins in each pile: ";
for (int i = 0; i < n; i++) {
cin >> piles[i];
}
int minimumMoves = minMoves(piles, n);
cout << "Minimum number of moves required: " << minimumMoves << endl;
return 0;
}
Explanation:
#include <iostream>
: Includes the necessary library for input and output operations.using namespace std;
: Declares that the program will use the standard C++ namespace for simpler access to standard library functions.int minMoves(int a[], int n)
: Defines a functionminMoves
that takes an arraya
and its sizen
as parameters and returns an integer.int moves = 0, sum = 0;
: Declares two integer variablesmoves
andsum
and initializes them to 0.for (int i = 0; i < n; i++)
: Initializes a loop that iterates through each element of the array.sum += a[i];
: Adds each element of the arraya
to the variablesum
.int avg = sum / n;
: Calculates the average value of the elements in the array by dividing the sum by the number of elements.for (int i = 0; i < n; i++)
: Initiates another loop through the array elements.if (a[i] > avg)
: Checks if the current element is greater than the calculated average.moves += (a[i] - avg);
: Calculates the surplus of coins in the pile compared to the average and adds it to themoves
variable.return moves;
: Returns the total number of moves required.int main()
: Starts the main function.int n;
: Declares an integer variablen
to store the number of piles.cout << "Enter the number of piles: ";
: Outputs a message to prompt the user to input the number of piles.cin >> n;
: Takes the user input for the number of piles and stores it in the variablen
.int piles[n];
: Declares an arraypiles
of sizen
to store the number of coins in each pile.cout << "Enter the number of coins in each pile: ";
: Outputs a message to prompt the user to input the number of coins in each pile.for (int i = 0; i < n; i++)
: Initiates a loop to take input for the number of coins in each pile.cin >> piles[i];
: Takes user input for the number of coins in each pile and stores them in thepiles
array.int minimumMoves = minMoves(piles, n);
: Calls theminMoves
function with thepiles
array and the number of piles as arguments and stores the result inminimumMoves
.cout << "Minimum number of moves required: " << minimumMoves << endl;
: Outputs the minimum number of moves required to equalize the piles of coins.