A permutation of integers is called beautiful if there are no adjacent elements whose difference is .
Given , construct a beautiful permutation if such a permutation exists.
Example:
Input: n = 5
Output: 2 4 1 3 5
Approach
Java
public class Permutations {public static void main(String[] args) {long n = 5;permutations(n);}static void permutations(long n) {if (n <= 3 && n != 1)System.out.println("NO SOLUTION");else {for (int i = 2; i <= n; i += 2)System.out.print(i + " ");for (int i = 1; i <= n; i += 2)System.out.print(i + " ");}}}
C++
#include <bits/stdc++.h>using namespace std;void permutations(long long n){if (n <= 3 && n != 1)cout << "NO SOLUTION\n";else{for (long long i = 2; i <= n; i += 2)cout << i << " ";for (long long i = 1; i <= n; i += 2)cout << i << " ";cout << "\n";}}int main(){long long n = 5;permutations(n);return 0;}
No comments:
Post a Comment