public int CreateSortedArray(int[] instructions) { var ans = 0; var mod = (int)1e9 + 7; // the idea is to store number of element // less then current in a segment array (power of twos) var tree = new Segments((int)1e5 + 1); for (int i = 0; i < instructions.Length; i++) { var less = tree.Get(instructions[i] - 1); var greater = i - tree.Get(instructions[i]); tree.Add(instructions[i]); ans += Math.Min(less, greater); ans %= mod; } return(ans); }