I recently came across problem 1861D and I'm having trouble understanding the solution provided by one of the users . The solution is given below:
Link to question -> ((http://codeforces.net/contest/1861/problem/D)
#include<bits/stdc++.h>
using namespace std;
int t,n,a[200005];
int main(){
cin>>t;
while(t--){
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
}
int ans=INT_MAX,a2=0,a1=0;
for(int i=1;i<n;i++)if(a[i]>=a[i+1])a2++;
ans=min(ans,a2);
for(int i=1;i<n;i++){
if(a[i]>=a[i-1])a1++;
if(a[i]>=a[i+1])a2--;
ans=min(ans,a2+a1);
}
cout<<ans<<"\n";
}
return 0;
}
Could you please explain how this solution works? Specifically, I'm having trouble understanding the logic behind the a1 and a2 variables and how they are used to calculate the minimum number of operations needed to sort the array in strictly ascending order.