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
相关推荐
林间码客30 分钟前
04 ROC曲线与AUC:从零开始手动计算
大数据·人工智能·算法
Irissgwe35 分钟前
map/set/multimap/multiset 的底层逻辑与实现
数据结构·c++·算法·二叉树·stl·c·红黑树
IronMurphy38 分钟前
【算法五十八】23. 合并 K 个升序链表
数据结构·算法·链表
思茂信息1 小时前
CST软件基于液态金属开关的方向图可重构天线
服务器·算法·重构·cst·仿真软件·电磁仿真
月疯1 小时前
PPG研究中暑的算法记录
算法
春日见1 小时前
vscode的AI编程插件推荐:
大数据·ide·vscode·算法·机器学习·编辑器·ai编程
blxr_1 小时前
力扣hot100路径总和Ⅲhttps://leetcode.cn/problems/path-sum-iii/
算法·leetcode·职场和发展
noipp2 小时前
【无标题】
c语言·数据结构·c++·算法
渡众机器人2 小时前
第八届全球校园人工智能算法精英大赛-算法应用赛-渡众机器人智能体对抗挑战赛规则
人工智能·算法·机器人·自动驾驶·自主导航·对抗赛
郝学胜-神的一滴3 小时前
完全二叉树与堆底层原理深度剖析 | 手写C++大顶堆实现
java·开发语言·数据结构·c++·python·算法