[LeetCode] Create Sorted Array through Instructions

1649. Create Sorted Array through Instructions

Given an integer array instructions, you are asked to create a sorted array from the elements in instructions. You start with an empty container nums. For each element from left to right in instructions, insert it into nums. The cost of each insertion is the minimum of the following:

  • The number of elements currently in nums that are strictly less than instructions[i].
  • The number of elements currently in nums that are strictly greater than instructions[i].

For example, if inserting element 3 into nums = [1,2,3,5], the cost of insertion is min(2, 1) (elements 1 and 2 are less than 3, element 5 is greater than 3) and nums will become [1,2,3,3,5].

Return the total cost to insert all elements from instructions into nums. Since the answer may be large, return it modulo 109 + 7

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
class Solution {
int fenwick[100001];
int mod = 1e9 + 7;
void update(int n) {
while(n < 100001) {
fenwick[n] += 1;
n += n & -n;
}
}
int qry(int n) {
int res = 0;
while(n > 0) {
res += fenwick[n];
n -= n & -n;
}
return res;
}
public:
int createSortedArray(vector<int>& N) {
long res = 0;
for(auto& n : N) {
int less = qry(n - 1);
int greater = qry(100000) - qry(n);
res = (res + min(less, greater)) % mod;
update(n);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/01/PS/LeetCode/create-sorted-array-through-instructions/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.