Beautiful Arrangement II

Given two integers n and k, you need to construct a list that contains n different positive integers ranging from 1 to n and obeys the following requirement:
Suppose this list is [a1, a2, a3, ... , an], then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] has exactly k distinct integers.

If there are multiple answers, print any of them.

Example:

Input: n = 3, k = 2
Output: [1, 3, 2]
Explanation: 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.

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

vector<intconstructArray(int nint k)
{
    vector<intres;
    for (int i = 0i <= k; ++i)
    {
        if (i == 0)
        {
            res.push_back(1);
        }
        else if (i == 1)
        {
            res.push_back(k + 1);
        }
        else if (i % 2 == 0)
        {
            res.push_back(res[i - 2] + 1);
        }
        else
        {
            res.push_back(res[i - 2] - 1);
        }
    }

    for (int i = k + 1i < n; ++i)
    {
        res.push_back(i + 1);
    }

    return res;
}

int main()
{
    int n = 3k = 2;

    vector<intres = constructArray(nk);

    cout << "[";
    for (int i = 0i < res.size(); i++)
    {
        cout << res[i];
        if (i != res.size() - 1)
            cout << ",";
    }
    cout << "]";

    return 0;
}


No comments:

Post a Comment