Beautiful Arrangement II in C++

C++Server Side ProgrammingProgramming

Suppose we have two integers n and k, we need to construct a list that contains n different positive integers ranging from 1 to n and obeys the following rule −

Consider the list is [a1, a2, a3, ... , an], then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] has exactly k unique integers. So if there are multiple answers, display any of them.

If the input is like n = 3 and k = 2, then the result will be [1,3,2]. The [1,3,2] has three different positive integers ranging from 1 to 3. And the [2,1] has exactly 2 distinct integers 1 and 2.

To solve this, we will follow these steps −

  • Define an array ret
  • for i := 1, j := n, check whether i <= j
    • if k > 1, then
      • if k is odd, then insert i otherwise insert j into ret
      • if k is odd, then increase i by 1, otherwise decrease j by 1
      • decrease k by 1
    • otherwise insert i into res and increase i by 1
  • 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<int> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
   public:
   vector<int> constructArray(int n, int k) {
      vector <int> ret;
      for(int i = 1, j = n; i <= j; ){
         if(k > 1){
            ret.push_back(k % 2 ? i : j);
            if(k % 2 == 1){
               i++;
            }else j--;
            k--;
         } else {
            ret.push_back(i++);
        }
      }
      return ret;
   }
};
main(){
   Solution ob;
   print_vector(ob.constructArray(3, 2));
}

Input

3
2

Output

[3, 1, 2, ]
raja
Published on 04-May-2020 17:07:20
Advertisements