Leetcode::Maximum Length of Semi-Decreasing Subarrays

point

Design

Big O(time)

Code


class Solution {
public:
    int maxSubarrayLength(vector<int>& nums) {
        int n = nums.size();
        vector<pair<int,int> > vp;
        for(int i = 0; i < n; i++) vp.push_back({nums[i], i});

        sort(vp.begin(), vp.end());

        int ret = 0; // return 0 if there's no such subarrays
        int maxPos = -1;
        int holdMaxPosForSameVal = -1;
        for(int i = 0; i < n; i++) {
            int val = vp[i].first, id = vp[i].second;
            int d = ((id > maxPos) ? 0 : maxPos - id + 1);
            ret = max(ret, d);
            holdMaxPosForSameVal = max(holdMaxPosForSameVal, id);

            if (i == n-1) {
                // do nothing
            } else {
                if (val != vp[i+1].first) {
                    maxPos = max(maxPos, holdMaxPosForSameVal);
                    holdMaxPosForSameVal = -1;
                }
            }
        }
        return ret;
    }
};