Sorted Arrays

Alice has recently found an array containing N integers. As we all know Alice loves sorted arrays so, he wants to sort the array. To sort an array Alice can add 1 to any integer in the array in 1 move.

Alice wants to find a minimum number of moves needed to sort this array. Remember that after sorting the array, all elements in it should be distinct.

Example:

Input:  n = 3, A = {1, 6, 5}
Output: 2

Approach

C++

#include <bits/stdc++.h>
using namespace std;

long sortedArray(long nvector<long&A)
{
    long sum = 0x = 0;
    for (int i = 1i < ni++)
    {
        if (A[i] <= A[i - 1])
        {
            x = (A[i - 1] - A[i]) + 1;
            sum = sum + x;
            A[i] = A[i] + x;
        }
    }
    return sum;
}
int main()
{

    long n = 3;
    vector<longA = {165};

    cout << sortedArray(nA<< "\n";

    return 0;
}


No comments:

Post a Comment