

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Beautiful Arrangement II in C++
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
- if k > 1, then
- return ret
Let us see the following implementation to get better understanding −
Example
#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, ]
- Related Questions & Answers
- Beautiful Arrangement in C++
- Beautiful Arrangement of Numbers in JavaScript
- Beautiful Array in C++
- Program for printing array in Pendulum Arrangement.
- Determining beautiful number string in JavaScript
- How to look beautiful in 15 days?
- How to look beautiful without makeup?
- Permutations II in C++
- Subsets II in C++
- 4Sum II in Python
- Check if the array is beautiful in Python
- What are the beautiful untranslatable Hindi words?
- How to create beautiful and useful infographics
- Maximum height of triangular arrangement of array values in C++
- Find the arrangement of queue at given time in C++
Advertisements