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
相关推荐
无敌最俊朗@2 小时前
力扣hot100-206反转链表
算法·leetcode·链表
Kuo-Teng2 小时前
LeetCode 279: Perfect Squares
java·数据结构·算法·leetcode·职场和发展
王哈哈^_^2 小时前
YOLO11实例分割训练任务——从构建数据集到训练的完整教程
人工智能·深度学习·算法·yolo·目标检测·机器学习·计算机视觉
檐下翻书1733 小时前
从入门到精通:流程图制作学习路径规划
论文阅读·人工智能·学习·算法·流程图·论文笔记
CoderYanger3 小时前
B.双指针——3194. 最小元素和最大元素的最小平均值
java·开发语言·数据结构·算法·leetcode·职场和发展·1024程序员节
小曹要微笑4 小时前
STM32各系列时钟树详解
c语言·stm32·单片机·嵌入式硬件·算法
前进的李工5 小时前
LeetCode hot100:094 二叉树的中序遍历:从递归到迭代的完整指南
python·算法·leetcode·链表·二叉树
麦麦大数据6 小时前
F049 知识图谱双算法推荐在线学习系统vue+flask+neo4j之BS架构开题论文全源码
学习·算法·知识图谱·推荐算法·开题报告·学习系统·计算机毕业设计展示
兩尛7 小时前
215. 数组中的第K个最大元素
数据结构·算法·排序算法
952367 小时前
数据结构-堆
java·数据结构·学习·算法