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
相关推荐
不懒不懒7 小时前
【逻辑回归从原理到实战:正则化、参数调优与过拟合处理】
人工智能·算法·机器学习
一只大袋鼠7 小时前
分布式 ID 生成:雪花算法原理、实现与 MyBatis-Plus 实战
分布式·算法·mybatis
tobias.b7 小时前
408真题解析-2010-27-操作系统-同步互斥/Peterson算法
算法·计算机考研·408真题解析
寄存器漫游者7 小时前
数据结构 二叉树核心概念与特性
数据结构·算法
m0_706653237 小时前
跨语言调用C++接口
开发语言·c++·算法
皮皮哎哟7 小时前
数据结构:从队列到二叉树基础解析
c语言·数据结构·算法·二叉树·队列
一匹电信狗8 小时前
【高阶数据结构】并查集
c语言·数据结构·c++·算法·leetcode·排序算法·visual studio
愚者游世8 小时前
list Initialization各版本异同
开发语言·c++·学习·程序人生·算法
.小墨迹8 小时前
apollo中车辆的减速绕行,和加速超车实现
c++·学习·算法·ubuntu·机器学习
超级大只老咪8 小时前
DFS算法(回溯搜索)
算法