Approach
This is a raelly interesting problem. same problem with yesterdays daily but need to come up with a much faster method.
I was originally thinking that checking a vector to be sorted is O(N), and we can only done in O(N^2), and after reading one solution, I find that we only need to check the neigobers order, and count the number of ordered pairs. In this case, we can check O(1) to update the number of ordered pairs, and this can be done in O(1).
For exmaple, we have [2,1,4,5,6,7,8], the ordered pair count is 6, it is not ordered since we have 7 pairs in total and (2,1) is not a ordered pair. After merging the smallest sum, that is (2,1), we have [3,4,5,6,7,8], the the ordered pair count is 6, and the total pairs is 6, so it is ordered, and this can be done incrementally with O(1) in each loop.
Then the rest part is much more simple, we maintain a min heap, and get the mimimal sum, and check if this sum is valid. I suppose we choose a idx and its next is r, and the double linked list is somthing like l <-> idx <-> r <-> r2, we then need to check if nums[idx]+nums[r] is still sum, and we check if r != -1 (meaning that it is not the end one). We need to check this since the r may be merged before, and we did not update the sum (and we cannot do this acutally) in the prioirty queue.
Also notice that hte range may sum up to long long, so we need to handle it with ll.
Code
class Solution {
public:
using ll = long long;
int minimumPairRemoval(vector<int>& nums0) {
int n = nums0.size();
vector<ll> nums(n);
for(int i = 0 ; i < n ; ++i) nums[i] = nums0[i];
int sortCnt = 0;
vector<int> next(n, -1);
vector<int> prev(n, -1);
priority_queue<pair<ll,int>, vector<pair<ll,int>>, greater<pair<ll,int>>> pq; // {sum, idx} pair
for(int i = 1 ; i < n ; ++i) {
next[i-1] = i;
prev[i] = i-1;
pq.push({nums[i-1]+nums[i], i-1});
if(nums[i-1] <= nums[i]) ++sortCnt;
}
if(sortCnt == n-1) return 0; // already sorted
int rem = n; // remain count
while(rem > 1) {
auto [sum, idx] = pq.top();
pq.pop();
// l <-> idx <-> r <-> r2
int r = next[idx];
if(r == -1 || sum != nums[idx] + nums[r]) continue;
int l = prev[idx];
int r2 = next[r];
if(l != -1 && nums[l] > nums[idx] && nums[l] <= sum) ++sortCnt;
if(l != -1 && nums[l] <= nums[idx] && nums[l] > sum) --sortCnt;
if(nums[idx] <= nums[r]) --sortCnt;
if(r2 != -1 && nums[r] > nums[r2] && sum <= nums[r2]) ++sortCnt;
if(r2 != -1 && nums[r] <= nums[r2] && sum > nums[r2]) --sortCnt;
--rem;
if(sortCnt == rem-1) return n - rem;
if(l != -1) pq.push({nums[l]+sum, l});
if(r2 != -1) {
pq.push({sum+nums[r2], idx});
next[idx] = r2;
prev[r2] = idx;
} else {
next[idx] = -1;
}
nums[idx] = sum;
next[r] = -1;
}
return n - 1;
}
};