Skip to content

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

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  long long numberOfSubarrays(vector<int>& nums) {
    long ans = 0;
    vector<pair<int, int>> stack;

    for (const int num : nums) {
      while (!stack.empty() && stack.back().first < num)
        stack.pop_back();
      if (stack.empty() || stack.back().first != num)
        stack.emplace_back(num, 0);
      ans += ++stack.back().second;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public long numberOfSubarrays(int[] nums) {
    Deque<int[]> stack = new ArrayDeque<>();
    long ans = 0;
    int top = -1;

    for (final int num : nums) {
      while (!stack.isEmpty() && stack.peek()[0] < num)
        stack.pop();
      if (stack.isEmpty() || stack.peek()[0] != num)
        stack.push(new int[] {num, 0});
      ans += ++stack.peek()[1];
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def numberOfSubarrays(self, nums: list[int]) -> int:
    ans = 0
    stack = []

    for num in nums:
      while stack and stack[-1][0] < num:
        stack.pop()
      if not stack or stack[-1][0] != num:
        stack.append([num, 0])
      stack[-1][1] += 1
      ans += stack[-1][1]

    return ans