✅Simple | Best Explanation | O(n)
Intuition\n Describe your first thoughts on how to solve this problem. \nTo count the number of subarrays where the maximum element lies between given bounds le
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo count the number of subarrays where the maximum element lies between given bounds left and right, we can leverage a sliding window approach. The idea is to keep track of valid subarrays as we iterate through the array and reset counters when we encounter elements outside the bounds.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**Sliding Window:** Use two pointers, i and j, to create a sliding window. The pointer j iterates through the array, while i marks the start of a valid subarray.\n**Reset on Exceeding Bound:** If an element exceeds the upper bound right, reset i to j + 1 and reset preCount (which tracks the count of valid subarrays ending at the previous position).\n**Count Valid Subarrays:** If an element falls within the bounds [left, right], update preCount to the number of valid subarrays ending at j.\nAccumulate Counts: Add preCount to the total count for every element within the bounds.\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n    int numSubarrayBoundedMax(vector<int>& nums, int left, int right) {\n        int i=0,j=0;\n        int count=0,preCount=0;\n        while(j<nums.size()){\n            if(nums[j]>right){\n                preCount=0;\n                i=j+1;\n            }\n            else if(left<=nums[j] && nums[j]<=right){\n                preCount=j-i+1;\n            }\n            count=count+preCount;\n            j++;\n        }\n        return count;\n    }\n};\n```\nPlease Upvote \uD83D\uDC4A\uD83D\uDC47\n![image.png](https://assets.leetcode.com/users/images/1754323e-3cac-4009-8e90-82f65875935b_1721587169.8485732.png)\n
['Array', 'Two Pointers', 'C', 'C++', 'Java']