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
相关推荐
YuTaoShao7 分钟前
【LeetCode 每日一题】1292. 元素和小于等于阈值的正方形的最大边长
算法·leetcode·职场和发展
Remember_9937 分钟前
【数据结构】深入理解Map和Set:从搜索树到哈希表的完整解析
java·开发语言·数据结构·算法·leetcode·哈希算法·散列表
浅念-9 分钟前
C++第一课
开发语言·c++·经验分享·笔记·学习·算法
charlie11451419112 分钟前
现代嵌入式C++教程:对象池(Object Pool)模式
开发语言·c++·学习·算法·嵌入式·现代c++·工程实践
燃于AC之乐24 分钟前
我的算法修炼之路--8——预处理、滑窗优化、前缀和哈希同余,线性dp,图+并查集与逆向图
算法·哈希算法·图论·滑动窗口·哈希表·线性dp
格林威34 分钟前
多相机重叠视场目标关联:解决ID跳变与重复计数的 8 个核心策略,附 OpenCV+Halcon 实战代码!
人工智能·数码相机·opencv·算法·计算机视觉·分类·工业相机
郝学胜-神的一滴36 分钟前
深入理解网络分层模型:数据封包与解包全解析
linux·开发语言·网络·程序人生·算法
永远都不秃头的程序员(互关)36 分钟前
【K-Means深度探索(九)】K-Means与数据预处理:特征缩放与降维的重要性!
算法·机器学习·kmeans
源代码•宸41 分钟前
Golang原理剖析(逃逸分析)
经验分享·后端·算法·面试·golang··内存逃逸
重生之后端学习1 小时前
25. K 个一组翻转链表
java·数据结构·算法·leetcode·职场和发展