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
相关推荐
羊小猪~~35 分钟前
LLM--微调(Adapters,Prompt,Prefix)
算法·ai·大模型·llm·prompt·adapters·prefix
未来之窗软件服务41 分钟前
SenseVoicecpp ggml-hexagon.cpp大模型[AI人工智能(七十九)]—东方仙盟
人工智能·算法·仙盟创梦ide·东方仙盟
xiaoye-duck42 分钟前
《算法题讲解指南:动态规划算法--子数组系列》--25.单词拆分,26.环绕字符串中唯一的子字符串
c++·算法·动态规划
Fcy6481 小时前
算法基础详解(二)枚举算法——普通枚举与二进制枚举
算法·枚举算法
承渊政道1 小时前
【优选算法】(实战:栈、队列、优先级队列高频考题通关全解)
数据结构·c++·笔记·学习·算法·leetcode·宽度优先
py有趣1 小时前
力扣热门100题之将有序数组转为二叉搜索树
算法·leetcode
天若有情6731 小时前
Python精神折磨系列(完整11集·无断层版)
数据库·python·算法
凌波粒1 小时前
LeetCode--383.赎金信(哈希表)
java·算法·leetcode·散列表
xiaoye-duck1 小时前
《算法题讲解指南:动态规划算法--子数组系列》--23.等差数列划分,24.最长湍流子数组
c++·算法·动态规划
小O的算法实验室2 小时前
2026年SEVC,高密度仓库中结合任务分配的多AGV无冲突调度框架,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进