leetcode - 2444. Count Subarrays With Fixed Bounds

该篇文章描述了一个编程问题,给定一个整数数组和两个整数minK和maxK,要求找出数组中满足元素最小值等于minK且最大值等于maxK的子数组的数量。文章提供了一种解决方案,利用两个指针jbad、jmin和jmax跟踪关键位置,并分析了时间复杂度为O(n)和空间复杂度为O(1)的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

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 <= 10^5
1 <= nums[i], minK, maxK <= 10^6

Solution

Solved after help…

Use a jbad to keep track of the position that num < minK or num > maxK, and jmin denotes the position of minK, jmax denotes the position of maxK.
For every A[i], the subarray ends with A[i], and starts with anywhere between [jbad + 1, min(jmax, jmin)].

Time complexity: o ( n ) o(n) o(n)
Space complexity: o ( 1 ) o(1) o(1)

Code

class Solution:
    def countSubarrays(self, nums: List[int], minK: int, maxK: int) -> int:
        jbad, jmin, jmax = -1, -1, -1
        res = 0
        for i in range(len(nums)):
            if nums[i] == minK:
                jmin = i
            if nums[i] == maxK:
                jmax = i
            if nums[i] < minK or nums[i] > maxK:
                jbad = i
            res += max(0, min(jmin, jmax) - jbad)
        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值