Simplest approach conceptually? - n Choose 2
Intuition\n\nNumbers above the maximum bound (right) will never be included in any subarray, so just skip those. \n\nA number below the minimum (left) can be in
# Intuition\n\nNumbers above the maximum bound (right) will never be included in any subarray, so just skip those. \n\nA number below the minimum (left) can be included in a subarray, but it can\'t stand by itself, so just compute the total number of subarrays where all values are below the maximum, then subtract the number of subarrays formed exclusively by elements less than the minimum\n\n![Solution.png](https://assets.leetcode.com/users/images/270e584a-871b-44e9-88bd-78d5d556c0d4_1703886567.7257671.png)\n\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\n O(1)\n\n# Code\n```\nclass Solution {\n    fun numSubarrayBoundedMax(nums: IntArray, left: Int, right: Int): Int {\n        var subarrayCount = 0L\n        var j = 0\n        var countBelowMin = 0L\n        var countBelowMax = 0L\n        while (j <= nums.size) {\n            if (j == nums.size || nums[j] > right) {\n                subarrayCount += countBelowMax.numberOfSubarrays()\n                subarrayCount -= countBelowMin.numberOfSubarrays()\n                countBelowMax = 0L\n                countBelowMin = 0L\n            } else if (nums[j] < left) {\n                countBelowMax += 1\n                countBelowMin += 1\n            } else {\n                subarrayCount -= countBelowMin.numberOfSubarrays()\n                countBelowMin = 0L\n                countBelowMax += 1\n            }\n            j++\n        }\n\n        return subarrayCount.toInt()\n    }\n\n    private fun Long.numberOfSubarrays(): Long {\n        return (this + 1) * this / 2\n    }\n}\n```
['Kotlin']