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 (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<int> a = {7, 3, 9, 10};pair<int, int> arr[100005];for (int i = 0; i < n; i++){arr[i] = {a[i] - (n - i + 1), i};}sort(arr, arr + n);int f = 1;for (int i = 0; i < n - 1; i++){if (arr[i].first == arr[i + 1].first){f = 0;break;}}if (f == 0){cout << "NO\n";}else{cout << "YES\n";for (int i = 0; i < n; i++){cout << a[arr[i].second] +(arr[i].second - i)<< " ";}cout << "\n";}}
No comments:
Post a Comment