Sliding Window
They key is to keep on capturing the sliding window size whenever we get a number at end of sliding window that is in valid range.\n\nWhy does it work?\n1. If t
They key is to keep on capturing the sliding window size whenever we get a number at end of sliding window that is in valid range.\n\nWhy does it work?\n1. If the last element is found to be such a large number that it crosses the valid range (maxWindow > right) - In this case we reset our window. So the window with this state where max element in the subarray is greater than the RIGHT will always have a size of 1 because of reset.\n2. If the last element is found to be in range, then state of sliding window will be one of these - \n(a) The last element is in range and it is the max element\n(b) The last element is in range and it is not the max element\nFor case (a) we calculate the size of the sliding window and keep it in PREFIX so that future items who are smaller than the range keep on making subarray that passes through this END element => total count of the subarray would be PREFIX for this specific future item.\nFor case (b) we still calculate the size of the sliding window again and keep it in PREFIX because any future smaller item needs to just have this END item in its subarray to make the subarray valid.\n\nThe structure of the code is very similar to - \nhttps://leetcode.com/problems/count-number-of-nice-subarrays/\n\n\n```\n    public int NumSubarrayBoundedMax(int[] nums, int left, int right) \n    {\n        int start = 0;\n        int end = 0;\n        int subArrayCount = 0;\n        int maxWindow = Int32.MinValue;\n        int prefix = 0;\n        \n        while(end < nums.Length)\n        {\n            if(nums[end] > maxWindow)\n            {\n                maxWindow = nums[end];\n            }\n                        \n            if(maxWindow < left)\n            {\n                prefix = 0;\n            }\n            else if(maxWindow > right)\n            {\n                //reset window\n                start = end+1;\n                prefix = 0;\n                maxWindow = Int32.MinValue;\n            }\n            \n            //If last element is in the range then the window\'s max is not greater than right\n            if(nums[end] >= left && nums[end] <= right)\n            {\n                prefix = (end-start+1);\n            }\n            \n            //If the window is valid add the prefix to it as item at end will be a part of prefix number of subArrays\n            if(maxWindow >= left && maxWindow <= right)\n            {\n                subArrayCount += prefix;\n            }\n\n            end++;\n        }\n        \n        return subArrayCount;\n    }\n```
[]