2
public int[] tree; // Binary indexed Tree array4
// initialize a new Fenwick tree of size length5
public Fenwick(int length) {6
tree = new int[length];9
// Returns the sum of values in an array from range [0, i]10
public int sum(int i) {14
i = i - (i & -i); // flip the last set bit using 2's compliment19
// Returns sum of values in the given range [start, end]20
public int sumRange(int start, int end) {21
return sum(end) - sum(start - 1);24
// updates the value at index i by "k" in tree25
public void update(int i, int k) {26
while (i < tree.length) {28
i = i + (i & -i); // add last set bit34
public int createSortedArray(int[] instructions) {35
// check for valid instructions36
if (instructions.length == 0) {41
to check for values strictly greater than any ith value in the instructions, we42
need to find the largest value in the instructions, this will denote the range43
of values in the Fenwick tree46
for (int value : instructions) {53
initialize a Fenwick Tree structure to allow for the search of all values strictly less than and54
strictly greater than instructions[i].56
since we need the tree to be 1 indexed, we add 1 to max58
Fenwick tree = new Fenwick(max + 1);61
for (int i = 0; i < instructions.length; i++) {62
int current_value = instructions[i];64
// get all the values less and greater than current_value65
int strictly_less = tree.sumRange(0, current_value - 1);66
int strictly_greater = tree.sumRange(current_value + 1, max);69
cost += Math.min(strictly_less, strictly_greater);71
// cost may be large so we mod it with 10^9 + 772
cost = cost % ((int) 1e9 + 7);74
// update the current_value's count in the FW tree75
tree.update(current_value, 1);