forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCreate Sorted Array through Instructions.java
79 lines (66 loc) · 2.43 KB
/
Create Sorted Array through Instructions.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
class Fenwick {
public int[] tree; //Binary indexed Tree array
//initialize a new Fenwick tree of size length
public Fenwick(int length) {
tree = new int[length];
}
//Returns the sum of values in an array from range [0, i]
public int sum(int i) {
int sum = 0;
while(i > 0) {
sum += tree[i];
i = i - (i & -i); //flip the last set bit using 2's compliment
}
return sum;
}
//Returns sum of values in the given range [start, end]
public int sumRange(int start, int end) {
return sum(end) - sum(start - 1);
}
//updates the value at index i by "k" in tree
public void update(int i, int k) {
while(i < tree.length) {
tree[i] += k;
i = i + (i & -i); //add last set bit
}
}
}
class Solution {
public int createSortedArray(int[] instructions) {
//check for valid instructions
if(instructions.length == 0) {
return 0;
}
/*
to check for values strictly greater than any ith value in the instructions, we
need to find the largest value in the instructions, this will denote the range
of values in the Fenwick tree
*/
int max = 0;
for(int value : instructions) {
if(value > max) {
max = value;
}
}
/*
initialize a Fenwick Tree structure to allow for the search of all values strictly less than and
strictly greater than instructions[i].
since we need the tree to be 1 indexed, we add 1 to max
*/
Fenwick tree = new Fenwick(max + 1);
int cost = 0;
for(int i = 0; i < instructions.length;i++) {
int current_value = instructions[i];
//get all the values less and greater than current_value
int strictly_less = tree.sumRange(0, current_value - 1);
int strictly_greater = tree.sumRange(current_value + 1, max);
//update cost
cost += Math.min(strictly_less, strictly_greater);
//cost may be large so we mod it with 10^9 + 7
cost = cost % ((int)1e9 + 7);
//update the current_value's count in the FW tree
tree.update(current_value, 1);
}
return cost;
}
}