Beautiful Array in C++

C++Server Side ProgrammingProgramming

Suppose for some fixed value of N, an array A is beautiful when it is a permutation of the integers 1, 2, ..., N, such that −

  • For every i < j, there is no such k with i < k < j such that A[k] * 2 = A[i] + A[j].

Suppose we have N, we have to find any beautiful array A.

So if the input is like 5, then the output will be [3,1,2,5,4]

To solve this, we will follow these steps −

  • Create one array called ret, insert 1 into ret

  • while size of ret < N

    • create an array temp

    • for i in range 0 to size of ret – 1

      • if ret[i] * 2 – 1 <= N, then insert ret[i] * 2 – 1 into temp array

    • for i in range 0 to size of ret – 1

    • if ret[i] * 2 <= N, then insert ret[i] * 2 into temp array

    • set ret := temp

  • return ret

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
   public:
   vector<int> beautifulArray(int N) {
      vector <int> ret;
      ret.push_back(1);
      while(ret.size() < N){
         vector <int> temp;
         for(int i = 0; i < ret.size(); i++){
            if(ret[i] * 2 - 1 <= N) temp.push_back(ret[i] * 2 - 1);
         }
         for(int i = 0; i < ret.size(); i++){
            if(ret[i] * 2 <= N)temp.push_back(ret[i] * 2 );
         }
         ret = temp;
      }
      return ret;
   }
};
main(){
   Solution ob;
   print_vector(ob.beautifulArray(6));
}

Input

5

Output

[1,5,3,2,4]
raja
Published on 10-Apr-2020 13:41:44
Advertisements