Leetcode 795: Number of Subarrays with Bounded Maximum

grid47
grid47
Exploring patterns and algorithms
Aug 19, 2024 6 min read

A sequence of numbers where subarrays are counted with a bounded maximum, glowing softly as each valid subarray is found.
Solution to LeetCode 795: Number of Subarrays with Bounded Maximum Problem

Given an integer array nums and two integers left and right, return the number of contiguous non-empty subarrays such that the maximum value in each subarray lies within the inclusive range [left, right].
Problem
Approach
Steps
Complexity
Input: You are given an integer array `nums` of size `n`, and two integers `left` and `right` that represent the range of valid maximum values for the subarrays.
Example: Input: nums = [1, 2, 3], left = 2, right = 3
Constraints:
• 1 <= nums.length <= 10^5
• 0 <= nums[i] <= 10^9
• 0 <= left <= right <= 10^9
Output: Return an integer representing the number of valid subarrays where the maximum value lies within the range [left, right].
Example: Output: 4
Constraints:
• The answer will always fit within a 32-bit integer.
Goal: The goal is to count all contiguous subarrays such that the maximum element in each subarray falls within the given range [left, right].
Steps:
• Initialize a variable `ans` to keep track of the number of valid subarrays.
• Iterate through each element of `nums` while maintaining a variable `dp` to count valid subarrays ending at the current index.
• If the current element is less than `left`, add `dp` to `ans` since the subarray formed up to this element is valid.
• If the current element is greater than `right`, reset `dp` as this element and any subarray containing it are no longer valid.
• If the current element is within the range [left, right], calculate `dp` as the number of valid subarrays that can be formed with the current element and add it to `ans`.
Goal: Ensure that the input values and array size fall within the provided constraints.
Steps:
• The length of `nums` should be at least 1 and at most 10^5.
• Each element in `nums` should be a non-negative integer not exceeding 10^9.
• Both `left` and `right` should lie between 0 and 10^9, inclusive.
Assumptions:
• The array `nums` is non-empty and contains integers.
• The range [left, right] is valid and falls within the specified bounds.
Input: Input: nums = [1, 2, 3], left = 2, right = 3
Explanation: There are four subarrays where the maximum element lies between 2 and 3: [2], [2, 3], [3], and [1, 2, 3].

Input: Input: nums = [2, 9, 2, 5, 6], left = 2, right = 8
Explanation: The valid subarrays are [2], [2, 9], [9], [2, 9, 2], [2, 9, 2, 5], [9, 2], and [2]. The total count is 7.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus