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
相关推荐
拳里剑气25 分钟前
C++算法:BFS解决FloodFill算法
c++·算法·bfs·宽度优先
wanderist.2 小时前
Lambda表达式在算法竞赛中的应用
java·开发语言·算法
稚南城才子,乌衣巷风流2 小时前
支配树(Dominator Tree)详解:概念、算法与应用
算法
稚南城才子,乌衣巷风流3 小时前
动态开点:原理、实现与应用场景
数据结构·算法
yyds_yyd_100863 小时前
1464. 数组中两元素的最大乘积(2026.07.27)
数据结构·c++·算法·leetcode
KaMeidebaby4 小时前
卡梅德生物技术快报 | 核酸适配体文库测序:核酸适配体文库测序的技术原理、实验流程与数据解析
前端·网络·数据库·人工智能·算法
geovindu5 小时前
CSharp: Breadth First Search Algorithm and Depth First Search Algorithm
开发语言·后端·算法·c#·.net·搜索算法
ekkoalex6 小时前
训练框架以及算法实现的框架
算法
DFT计算杂谈6 小时前
交错磁研究进展材料物性与交叉应用
数据库·人工智能·python·opencv·算法