LeetCode-in-Java

3676. 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:

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].

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:

Solution

public class Solution {
    public long bowlSubarrays(int[] nums) {
        int n = nums.length;
        int res = n;
        int pre = 0;
        for (int a : nums) {
            if (a > pre) {
                res--;
                pre = a;
            }
        }
        pre = 0;
        for (int i = n - 1; i >= 0; i--) {
            if (nums[i] > pre) {
                res--;
                pre = nums[i];
            }
        }
        return res + 1L;
    }
}