The second solution can be done in O(nlgn)
time using a merge sort technique. Below is the code
[#include](https://leetcode.com/problems/minimum-interval-to-include-each-query) <bits/stdc++.h>
using namespace std;
int inv;
vector<int>merge_cnt(vector<int>a, vector<int>b){
if(a.empty())return b;
if(b.empty())return a;
int n = (int)a.size();
int m = (int)b.size();
a.push_back(INT_MAX);
b.push_back(INT_MAX);
int i = 0, j = 0;
vector<int>fin;
while(i<n || j<m){
if(a[i]<=b[j]){
fin.push_back(a[i]);
++i;
}else{
inv += n-i;
fin.push_back(b[j]);
++j;
}
}
return fin;
}
vector<int> merge_sort(vector<int>a){
if(a.empty())return {};
int n = (int)a.size();
if(n == 1 )return a;
vector<int>left, right;
for(int i = 0; i<(n+1)/2; ++i){
left.push_back(a[i]);
}
for(int i = (n+1)/2; i<n; ++i){
right.push_back(a[i]);
}
left = merge_sort(left);
right = merge_sort(right);
// how to check if this is the first call?
auto ans = merge_cnt(left, right);
return ans;
}
int main() {
vector<int>a = {5, 6, 7, 1, 2, 3};
// a = { 1, 20, 6, 4, 5 };
a = merge_sort(a);
for(auto&it:a)cout<<it<<" ";
cout<<"\n";
cout<<"Inversion = "<<inv<<endl;
cout<<"\n";
return 0;
}