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 function minMoves that takes an array a and its size n as parameters and returns an integer.
  • int moves = 0, sum = 0;: Declares two integer variables moves and sum 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 array a to the variable sum.
  • 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 the moves variable.
  • return moves;: Returns the total number of moves required.
  • int main(): Starts the main function.
  • int n;: Declares an integer variable n 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 variable n.
  • int piles[n];: Declares an array piles of size n 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 the piles array.
  • int minimumMoves = minMoves(piles, n);: Calls the minMoves function with the piles array and the number of piles as arguments and stores the result in minimumMoves.
  • cout << "Minimum number of moves required: " << minimumMoves << endl;: Outputs the minimum number of moves required to equalize the piles of coins.