|
| 1 | +3748\. Count Stable Subarrays |
| 2 | + |
| 3 | +Hard |
| 4 | + |
| 5 | +You are given an integer array `nums`. |
| 6 | + |
| 7 | +A ****non-empty subarrays**** of `nums` is called **stable** if it contains **no inversions**, i.e., there is no pair of indices `i < j` such that `nums[i] > nums[j]`. |
| 8 | + |
| 9 | +You are also given a **2D integer array** `queries` of length `q`, where each <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code> represents a query. For each query <code>[l<sub>i</sub>, r<sub>i</sub>]</code>, compute the number of **stable subarrays** that lie entirely within the segment <code>nums[l<sub>i</sub>..r<sub>i</sub>]</code>. |
| 10 | + |
| 11 | +Return an integer array `ans` of length `q`, where `ans[i]` is the answer to the <code>i<sup>th</sup></code> query. |
| 12 | + |
| 13 | +**Note**: |
| 14 | + |
| 15 | +* A single element subarray is considered stable. |
| 16 | + |
| 17 | +**Example 1:** |
| 18 | + |
| 19 | +**Input:** nums = [3,1,2], queries = [[0,1],[1,2],[0,2]] |
| 20 | + |
| 21 | +**Output:** [2,3,4] |
| 22 | + |
| 23 | +**Explanation:** |
| 24 | + |
| 25 | +* For `queries[0] = [0, 1]`, the subarray is `[nums[0], nums[1]] = [3, 1]`. |
| 26 | + * The stable subarrays are `[3]` and `[1]`. The total number of stable subarrays is 2. |
| 27 | +* For `queries[1] = [1, 2]`, the subarray is `[nums[1], nums[2]] = [1, 2]`. |
| 28 | + * The stable subarrays are `[1]`, `[2]`, and `[1, 2]`. The total number of stable subarrays is 3. |
| 29 | +* For `queries[2] = [0, 2]`, the subarray is `[nums[0], nums[1], nums[2]] = [3, 1, 2]`. |
| 30 | + * The stable subarrays are `[3]`, `[1]`, `[2]`, and `[1, 2]`. The total number of stable subarrays is 4. |
| 31 | + |
| 32 | +Thus, `ans = [2, 3, 4]`. |
| 33 | + |
| 34 | +**Example 2:** |
| 35 | + |
| 36 | +**Input:** nums = [2,2], queries = [[0,1],[0,0]] |
| 37 | + |
| 38 | +**Output:** [3,1] |
| 39 | + |
| 40 | +**Explanation:** |
| 41 | + |
| 42 | +* For `queries[0] = [0, 1]`, the subarray is `[nums[0], nums[1]] = [2, 2]`. |
| 43 | + * The stable subarrays are `[2]`, `[2]`, and `[2, 2]`. The total number of stable subarrays is 3. |
| 44 | +* For `queries[1] = [0, 0]`, the subarray is `[nums[0]] = [2]`. |
| 45 | + * The stable subarray is `[2]`. The total number of stable subarrays is 1. |
| 46 | + |
| 47 | +Thus, `ans = [3, 1]`. |
| 48 | + |
| 49 | +**Constraints:** |
| 50 | + |
| 51 | +* <code>1 <= nums.length <= 10<sup>5</sup></code> |
| 52 | +* <code>1 <= nums[i] <= 10<sup>5</sup></code> |
| 53 | +* <code>1 <= queries.length <= 10<sup>5</sup></code> |
| 54 | +* <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code> |
| 55 | +* <code>0 <= l<sub>i</sub> <= r<sub>i</sub> <= nums.length - 1</code> |
0 commit comments