Home

The Sorted Array

Adi loves to play with arrays. He simply wants to sort this array in increasing order.

For doing this he can swap any two adjacent elements i.e. a[i] and a[i+1] where  1iN1 (1 based indexing).

In swapping the value of a[i] decreases by 1 while a[i+1] increases by 1. This operation can be applied any number of times he wants. Can you help him find the final sorted array?

Example:

Input:  n = 4, a = {7, 3, 9, 10}

Output:

YES 4 6 9 10

Approach:

C++

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

int main()
{

    int n = 4;

    vector<inta = {73910};
    pair<intintarr[100005];

    for (int i = 0i < ni++)
    {

        arr[i= {a[i] - (n - i + 1), i};
    }

    sort(arrarr + n);
    int f = 1;
    for (int i = 0i < n - 1i++)
    {
        if (arr[i].first == arr[i + 1].first)
        {
            f = 0;
            break;
        }
    }
    if (f == 0)
    {
        cout << "NO\n";
    }
    else
    {
        cout << "YES\n";
        for (int i = 0i < ni++)
        {
            cout << a[arr[i].second] +
                        (arr[i].second - i)
                 << " ";
        }
        cout << "\n";
    }
}


No comments:

Post a Comment