Try   HackMD

2444.Count Subarrays With Fixed Bounds

tags: Hard,Array,Queue,Sliding Window

2444. Count Subarrays With Fixed Bounds

題目描述

You are given an integer array nums and two integers minK and maxK.

A fixed-bound subarray of nums is a subarray that satisfies the following conditions:

  • The minimum value in the subarray is equal to minK.
  • The maximum value in the subarray is equal to maxK.

Return the number of fixed-bound subarrays.

A subarray is a contiguous part of an array.

範例

Example 1:

Input: nums = [1,3,5,2,7,5], minK = 1, maxK = 5
Output: 2
Explanation: The fixed-bound subarrays are [1,3,5] and [1,3,5,2].

Example 2:

Input: nums = [1,1,1,1], minK = 1, maxK = 1
Output: 10
Explanation: Every subarray of nums is a fixed-bound subarray. There are 10 possible subarrays.

Constraints:

  • 2 <= nums.length <= 105
  • 1 <= nums[i], minK, maxK <= 106

解答

C++

思路:
  1. 找subarray符合最大值等於maxK, 最小值等於minK
  2. 看constraint基本上為要求O(n)解法
  3. 思考從0遍歷至index i時, 若為合法subarray, 則其前面必有maxK及minK出現, 而此時考慮可以新增的subarray個數為maxK跟minK取最遠的index, 跟不符合條件的index(boundary)做相減算合法的個數, 即為此次可新增的個數, 遍歷累加即可
  4. 遍歷時紀錄maxK/minK/boundary index即可
class Solution { public: long long countSubarrays(vector<int>& nums, int minK, int maxK) { long long res = 0; int minKIndex = -1, maxKIndex = -1, boundary = -1; for(int i = 0; i < nums.size(); i++) { if(nums[i] < minK || nums[i] > maxK) { boundary = i; continue; } if(nums[i] == minK) minKIndex = i; if(nums[i] == maxK) maxKIndex = i; res += max(0, min(minKIndex, maxKIndex) - boundary); } return res; } };

Time:

O(n)
Extra Space:
O(1)

XD March 4, 2023

Reference

回到題目列表