package leetcode;

import java.util.Arrays;

/**
 * https://leetcode.com/problems/beautiful-arrangement-ii/
 */
public class Problem667 {
    public int[] constructArray(int n, int k) {
        int[] result = new int[n];
        int idx = 0;
        for (int i = 0; i < n; i++) {
            if (i == 0) {
                result[idx++] = i + 1;
                continue;
            }
            if (k > 0) {
                int a = result[i - 1] - k;
                if (a <= 0) {
                    a = result[i - 1] + k;
                }
                result[idx++] = a;
                k--;
            } else {
                result[idx++] = result[i - 1] + 1;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        Problem667 prob = new Problem667();
        System.out.println(Arrays.toString(prob.constructArray(3, 1))); // [1,2,3]
        System.out.println(Arrays.toString(prob.constructArray(3, 2))); // [1,3,2]
        System.out.println(Arrays.toString(prob.constructArray(10, 9))); // [1,10,2,9,3,8,4,7,5,6]
        System.out.println(Arrays.toString(prob.constructArray(10, 5))); // [1,6,2,5,3,4,7,8,9,10]
    }
}

@@ -16,34 +16,8 @@
 e;%0A%0A
-import java.util.Arrays;%0A%0A
 /**%0A
@@ -209,16 +209,63 @@
 dx = 0;%0A
+        boolean add = true;%0A        int j = k;%0A
         
@@ -415,17 +415,17 @@
     if (
-k
+j
  %3E 0) %7B%0A
@@ -449,28 +449,8 @@
 nt a
- = result%5Bi - 1%5D - k
 ;%0A  
@@ -472,13 +472,10 @@
 f (a
- %3C= 0
+dd
 ) %7B%0A
@@ -514,17 +514,50 @@
  - 1%5D + 
-k
+j;%0A                    add = false
 ;%0A      
@@ -559,33 +559,43 @@
                %7D
-%0A
+ else %7B%0A   
                 
@@ -585,32 +585,37 @@
                 
+  a =
  result%5Bidx++%5D =
@@ -611,19 +611,21 @@
 lt%5Bi
-dx++%5D = a;%0A
+ - 1%5D - j;%0A  
     
@@ -640,11 +640,20 @@
     
-k--
+  add = true
 ;%0A  
@@ -658,32 +658,29 @@
             
-%7D else %7B
+    %7D
 %0A           
@@ -704,40 +704,43 @@
 %5D = 
-result%5Bi - 1%5D + 1;%0A            %7D
+a;%0A            %7D else if (j == 0) %7B
 %0A   
@@ -736,34 +736,32 @@
 == 0) %7B%0A        
-%7D%0A
         return r
@@ -758,480 +758,172 @@
   re
-turn result
+sult%5Bidx++%5D = result%5B1%5D + 1
 ;%0A    
-%7D%0A%0A
     
-public static void main(String%5B%5D args) %7B%0A        Problem667 prob = new Problem667();%0A        System.out.println(Arrays.toString(prob.constructArray(3, 1))); // %5B1,2,3%5D%0A        System.out.println(Arrays.toString(prob.constructArray(3, 2))); // %5B1,3,2%5D%0A        System.out.println(Arrays.toString(prob.constructArray(10, 9))); // %5B1,10,2,9,3,8,4,7,5,6%5D%0A        System.out.println(Arrays.toString(prob.constructArray(10, 5))); // %5B1,6,2,5,3,4,7,8,9,10%5D
+    %7D else %7B%0A                result%5Bidx++%5D = result%5Bi - 1%5D + 1;%0A            %7D%0A            j--;%0A        %7D%0A        return result;
 %0A   

Solve problem 667