Given an array (with all elements greater than 0), create a non-decreasing array by swapping 2 elements if their gcd(Greatest Common Factor) is equal to the minimum element of the array.
You have to print “YES” if this is possible, and if not print “NO”.
Examples:
Input: a[] = {6,2,4,8,12} Output: YES Explaination: Swap a[1] and a[2] and then swap a[0] and a[2] Input: a[] = {1,2,3,4,5} Output: YES Explaination: Array is already sorted
Approach:
- Find the minimum of array a[] say min.
- Find all the elements which is not at their position and check that it is divisible by min or not.
- If all elements which is not at its position is divisible by min print “YES “else “NO”.
Implementation in C++:
#include<bits/stdc++.h> using namespace std; int main() { int n, i, min, flag = 0; cin >> n; int a[n], b[n]; for (i = 0; i < n; i++) { cin >> a[i]; b[i] = a[i]; } sort(b, b + n); min = b[0]; for (i = 0; i < n; i++) { if (a[i] != b[i]) { if (b[i] % min != 0) { flag = 1; break; } } } if (flag == 1) cout << "NO" << endl; else { cout << "YES" << endl; } }
Input:
6,2,4,8,12
Output:
YES
Time complexity: O(n)