leetcode713. Subarray Product Less Than K

Given an array of integers nums and an integer k, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k.

Example 1:

Input: nums = 10,5,2,6, k = 100

Output: 8

Explanation: The 8 subarrays that have product less than 100 are:

10\], \[5\], \[2\], \[6\], \[10, 5\], \[5, 2\], \[2, 6\], \[5, 2, 6

Note that 10, 5, 2 is not included as the product of 100 is not strictly less than k.

Example 2:

Input: nums = 1,2,3, k = 0

Output: 0

思路:使用滑动窗口的思路,找取每一个符合条件的小窗,统计其内部子数组数量。

注意,对于某一个值,我们只关注以它为最右边元素的子数组。这样可以减少重复讨论的麻烦。

python 复制代码
class Solution:
    def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
        if k <= 1: return 0
        left, right, multi, ans = 0, 0, 1, 0
        while right < len(nums):
            multi *= nums[right] # 以右侧元素为pivot
            while multi >= k: # 找到对应这个pivot的最长窗口左侧点
                multi //= nums[left]
                left += 1
            ans += right - left + 1 # 统计以pivot为右侧元素的子数组
            right += 1
        return ans
相关推荐
ocean21037 小时前
2025-2026年AI算法与模型研发面试高频知识点洞察
人工智能·算法·面试
Nil2087 小时前
leetcode 78子集
数据结构·算法·leetcode
en.en..8 小时前
Linux fork() 工作原理
数据结构·算法
地平线开发者9 小时前
bevformer算法模型详细解读
算法
liliangcsdn9 小时前
ICIR权重矩阵如何加权标准化为综合因子
算法
SDWAN_Cheap10 小时前
SD-WAN智能选路技术的算法与实现机制
算法·php·sdwan
不会就选b10 小时前
数据结构之树&&二叉树(二)
数据结构·算法
渡之11 小时前
ArduPilot (APM)滤波器之SlewLimiter 深度解析
算法
zander25811 小时前
LeetCode 1143. 最长公共子序列
开发语言·python·算法
Sumerking11 小时前
llc_control.c 专项评审(v3 更新版)
c语言·开发语言·算法·obc