Skip to content

Commit 0aa263f

Browse files
authored
Create 1649.Create-Sorted-Array-through-Instructions_v2.cpp
1 parent ad1a34d commit 0aa263f

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
const int MAX_N = 100000;
2+
3+
class Solution {
4+
public:
5+
long long bitArr[MAX_N+1];
6+
long long nums[MAX_N+1];
7+
long long M = 1e9+7;
8+
9+
void updateDelta(int i, long long delta) {
10+
int idx = i;
11+
while (idx <= MAX_N)
12+
{
13+
bitArr[idx]+=delta;
14+
bitArr[idx] %= M;
15+
idx+=idx&(-idx);
16+
}
17+
}
18+
19+
long long queryPreSum(int idx){
20+
long long result = 0;
21+
while (idx){
22+
result += bitArr[idx];
23+
result %= M;
24+
idx-=idx&(-idx);
25+
}
26+
return result;
27+
}
28+
29+
long long sumRange(int i, int j) {
30+
return queryPreSum(j)-queryPreSum(i-1);
31+
}
32+
33+
int createSortedArray(vector<int>& instructions)
34+
{
35+
long long ret = 0;
36+
37+
for (auto x:instructions)
38+
{
39+
updateDelta(x, 1);
40+
long long a = sumRange(1, x-1);
41+
long long b = sumRange(x+1, MAX_N);
42+
ret += min(a,b);
43+
ret %= M;
44+
}
45+
return ret;
46+
47+
}
48+
};

0 commit comments

Comments
 (0)