Count Bowl Subarrays Problem
Description
LeetCode Problem 3676.
You are given an integer array nums with distinct elements.
A subarray nums[l...r] of nums is called a bowl if:
- The subarray has length at least 3. That is,
r - l + 1 >= 3. - The minimum of its two ends is strictly greater than the maximum of all elements in between. That is,
min(nums[l], nums[r]) > max(nums[l + 1], ..., nums[r - 1]).
Return the number of bowl subarrays in nums.
Example 1:
Input: nums = [2,5,3,1,4]
Output: 2
Explanation:
The bowl subarrays are [3, 1, 4] and [5, 3, 1, 4].
- [3, 1, 4] is a bowl because min(3, 4) = 3 > max(1) = 1.
- [5, 3, 1, 4] is a bowl because min(5, 4) = 4 > max(3, 1) = 3.
Example 2:
Input: nums = [5,1,2,3,4]
Output: 3
Explanation:
The bowl subarrays are [5, 1, 2], [5, 1, 2, 3] and [5, 1, 2, 3, 4].
Example 3:
Input: nums = [1000000000,999999999,999999998]
Output: 0
Explanation:
No subarray is a bowl.
Constraints:
3 <= nums.length <= 10^51 <= nums[i] <= 10^9numsconsists of distinct elements.
Solution
Approach: Monotonic Stack
In a bowl nums[l...r], both ends are larger than everything between them. So when we fix the right end r and look to the left, the possible left walls are the elements that are not hidden by a larger element closer to r. A decreasing stack holds exactly these elements.
Scan nums from left to right. For the new value x, pop every stack element smaller than x. When an element y is popped and the stack is still not empty, the new top z is larger than y, and y is the maximum of everything between z and x. Because y < x and y < z, the subarray from z to x is a bowl, so add one to the answer. Then push x.
Every bowl is counted exactly once: its interior maximum is popped exactly when its right end arrives, and its left end is the element right below it on the stack.
Complexity: O(n) time and O(n) extra space, where n is the length of nums.
class Solution:
def bowlSubarrays(self, nums: List[int]) -> int:
stk = [] # decreasing stack of candidate left walls
ans = 0
for x in nums:
while stk and stk[-1] < x:
stk.pop()
if stk: # the popped value is the interior maximum, stk[-1] is a valid left wall
ans += 1
stk.append(x)
return ans