Formula Based Approach
Code\n\nclass Solution {\npublic:\n    int semiOrderedPermutation(vector<int>& nums) {\n        int n=nums.size();\n        int mx=0, mxidx=0;\n        int mn=I
# Code\n```\nclass Solution {\npublic:\n    int semiOrderedPermutation(vector<int>& nums) {\n        int n=nums.size();\n        int mx=0, mxidx=0;\n        int mn=INT_MAX, mnidx;\n        int count=0;\n\n        for(int i=0; i<n; i++){\n            mx=max(mx, nums[i]);\n            if(nums[i]==mx) mxidx=i;\n\n            mn=min(mn, nums[i]);\n            if(nums[i]==mn) mnidx=i;\n        }\n        \n        count=n+mnidx-mxidx-1;\n        if(mnidx<mxidx) return count;\n        return --count;\n            \n    }\n};\n```
['C++']