
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 Articles
- Beautiful Arrangement in C++
- Beautiful Arrangement of Numbers in JavaScript
- Beautiful Array in C++
- Determining beautiful number string in JavaScript
- A Truly Beautiful Mind
- How to look beautiful in 15 days?
- Check if the array is beautiful in Python
- How to look beautiful without makeup?
- What is the most beautiful thing in the world?
- Program for printing array in Pendulum Arrangement.
- What are the beautiful untranslatable Hindi words?
- How to create beautiful and useful infographics
- The Summer of The Beautiful White Horse
- Techniques to Make Design Beautiful and Attractive
- Draw the electron-dot structure of a hydrogen chloride molecule:(i) Which inert gas does the H atom in HCl resemble in electron arrangement? (ii) Which inert gas does the Cl atom in HCl resemble in electron arrangement?

Advertisements