[CPP] O(N) time and O(1) space with explanation
\nstatic auto fast=[]{ios_base::sync_with_stdio(false);cin.tie(nullptr);return 0;}();\n#define mod 1000000007\nclass Solution \n{\npublic:\n    int numSubarrayB
```\nstatic auto fast=[]{ios_base::sync_with_stdio(false);cin.tie(nullptr);return 0;}();\n#define mod 1000000007\nclass Solution \n{\npublic:\n    int numSubarrayBoundedMax(vector<int>& A, int L, int R) \n    {\n        //for an element there are 3 cases possible:\n        //case 1 :element is greater than R. In this case,there will be no valid subarrays ending with this element\n        //        because all the subarrays ending with this element will have a maximum value >=current element \n        //        hence will not be valid.\n        //case 2: element is less than L. In this case element itself will not form a valid subarray but can append\n        //        to all the valid subarrays ending with previous element.hence number of valid subarrays ending \n        //        with current element will be equal to the number of valid subarrays ending with previous element.\n        //        this is possible because a valid subarray will have maximum value at least L and at most R and since\n        //        current element\'s value is less than L,max value of the subarray will not be changed when this element\n        //        is appended to the end.\n        //case 3: element at least L and at most R.In this case element itself will form a valid subarray plus it will\n        //        also form other valid subarrays as follows: we\'ll look for recent/latest element having value >R.all\n        //        the elements between this element and current element(including current element) will form valid sub-\n        //        -arrays ending with current element.\n        \n        int ans=0;\n        int index=-1; //index of recent element having >R\n        int prev=0;   //number of valid subarrays ending with previous element\n        for(int i=0;i<A.size();i++)\n        {\n            if(A[i]>R)  //case 1\n            {\n               prev=0;\n               index=i; \n            }\n            else if(A[i]<L) //case 2\n            {\n               ans+=prev;\n               //prev=prev; \n            }\n            else //if(A[i]>=L&&A[i]<=R) //case 3\n            {\n               ans+=i-index;\n               prev=i-index; \n            }\n        }\n        return ans;\n    }\n};\n```
[]