Skip to content
LC-3113 Hard LeetCode

3113. Find the Number of Subarrays Where Boundary Elements Are Maximum

Read the full problem statement on LeetCode.
Difficulty: hard Acceptance: 31% Topics: Array, Binary Search, Stack, Monotonic Stack
View full problem on LeetCode
Reference solution (spoiler · python)
# Time:  O(n)
# Space: O(n)

# mono stack, combinatorics
class Solution(object):
    def numberOfSubarrays(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        result = 0
        stk = []
        for x in nums:
            while stk and stk[-1][0] < x:
                stk.pop()
            if not stk or stk[-1][0] != x:
                stk.append([x, 0])
            stk[-1][1] += 1
            result += stk[-1][1]
        return result

Solution from kamyu104/LeetCode-Solutions · MIT