Skip to content

4000. Count Bowl Subarrays


4000. Count Bowl Subarrays

Medium


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 <= 105
  • 1 <= nums[i] <= 109
  • nums consists of distinct elements.

Solution

class Solution {
    private int nextGreater[];
    private int prevGreater[];
    static class Pair {
        int node, idx;
        public Pair(int node, int idx) {
            this.node = node;
            this.idx = idx;
        }
    }
    public long bowlSubarrays(int[] nums) {
        int n = nums.length;

        buildNextGreater(nums);
        buildPrevGreater(nums);

        int ans = 0;
        for (int i = 0; i < n; i++) {
            if (nextGreater[i] != -1 && prevGreater[i] != -1) 
                ans++;
        } 
        return ans;
    }

    private void buildNextGreater(int arr[]) {
        int n = arr.length;
        nextGreater = new int[n];
        Stack<Pair> st = new Stack<>();
        for (int i = n - 1; i >= 0; i--) {
            int current = arr[i];
            while (st.size() > 0 && st.peek().node <= current) {
                st.pop();
            }
            if (st.size() == 0)
                nextGreater[i] = -1;
            else 
                nextGreater[i] = st.peek().idx;
            st.add(new Pair(current, i));
        }
    }

    private void buildPrevGreater(int arr[]) {
        int n = arr.length;
        prevGreater = new int[n];
        Stack<Pair> st = new Stack<>();
        for (int i = 0; i < n; i++) {
            int current = arr[i];
            while (st.size() > 0 && st.peek().node <= current) 
                st.pop();
            if (st.size() == 0)
                prevGreater[i] = -1;
            else 
                prevGreater[i] = st.peek().idx;
            st.add(new Pair(current, i));
        }
    }
}

Complexity Analysis

  • Time Complexity: O(?)
  • Space Complexity: O(?)

Explanation

[Add detailed explanation here]