C++ | Easy to understand | Pattern Discovery
Approach\n Describe your approach to solving the problem. \nObserve the pattern in this example then you will understand the solution better:\n\nExample : n = 6
# Approach\n<!-- Describe your approach to solving the problem. -->\nObserve the pattern in this example then you will understand the solution better:\n\nExample : n = 6; k= 1,2,3,4\n\n1 2 3 4 5 6 => 1 distinct; difference -> 1 1 1 1 1\n1 3 2 4 5 6 => 2 distinct; difference -> 1 3 2 1 1\n1 4 2 1 5 6 => 3 distinct; difference -> 3 2 1 1 1\n1 5 2 4 3 6 => 4 distinct; difference -> 4 3 2 1 3\n\n# Code\n```\nclass Solution {\npublic:\n    vector<int> constructArray(int n, int k) {\n        vector<int> v;\n        //Insert 1 => This is the base for creating the rest of the array\n        v.push_back(1);\n        int maxi = k;\n        int flag = 1; //1->increase, 0->decrease\n        while(v.size()<n && maxi){\n            //increase\n            if(flag){\n                int nextNum = v.back() + maxi;\n                v.push_back(nextNum);\n                maxi--;\n            }\n            //decrease\n            else{\n                int nextNum = v.back() - maxi;\n                v.push_back(nextNum);\n                maxi--;\n            }\n            flag = !flag;\n        }\n        //If maxi = 0 => Elements will repeat, push the left out elements after the maximum in ans\n        int i = *max_element(v.begin(),v.end());\n        i++;\n        while(v.size()<n){\n            v.push_back(i);\n            i++;\n        }\n        return v;\n    }\n};\n\n```
['Array', 'Math', 'C++']