leetcode - 713. Subarray Product Less Than K

Description

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

Constraints:

复制代码
1 <= nums.length <= 3 * 10^4
1 <= nums[i] <= 1000
0 <= k <= 10^6

Solution

Similar to 2302. Count Subarrays With Score Less Than K, every time when expanding the window, we introduce j - i + 1 new subarrays (with the nums[j] as the ending element)

Time complexity: o ( n ) o(n) o(n)

Space complexity: o ( 1 ) o(1) o(1)

Code

python3 复制代码
class Solution:
    def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
        cur_prod = 1
        i = 0
        res = 0
        for j in range(len(nums)):
            cur_prod *= nums[j]
            while i <= j and cur_prod >= k:
                cur_prod /= nums[i]
                i += 1
            res += j - i + 1
        return res
相关推荐
依然鸣几秒前
PTA团体程序设计天梯赛L2真题讲解L2-045-048
数据结构·c++·经验分享·学习·算法·pat考试·pat
丢掉幻想准备斗争6 分钟前
5.5树与二叉树的应用
算法
ZhouDevin31 分钟前
算法论文/模型微调2——仅骨干1%~3% 参数达到与全量微调相当的性能
算法
Sinosecu-OCR1 小时前
文通OCR技术深度解析:自研算法如何搞定复杂场景识别?
算法·ocr·ocr识别系统
CQU_JIAKE1 小时前
8.5【A】
数据结构·算法
ESBK20251 小时前
学术邀约|CMICA 2026 第二届计算方法、智能控制与航空航天国际会议
大数据·人工智能·算法·飞行器·智能控制·航空航天·计算
无bug代码搬运工2 小时前
LeetCode 42 接雨水:双指针解法详解
算法·leetcode·职场和发展
Jasmine_llq2 小时前
《P13016 [GESP202506 六级] 最大因数》
数据结构·算法
白狐_7982 小时前
考研408算法设计题保命策略:链表专题暴力解法精讲(2015 & 2019真题实战)
考研·算法·链表
fangpin2 小时前
GPU编程2: 并行策略
算法