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
相关推荐
Dave.B2 分钟前
【VTK核心过滤器详解】:vtkCleanPolyData 多边形数据清洗实战指南
算法·vtk
AiXed31 分钟前
PC微信 device uuid 算法
前端·算法·微信
@木辛梓1 小时前
指针,数组,变量
开发语言·c++·算法
苏纪云2 小时前
数据结构期中复习
数据结构·算法
flashlight_hi2 小时前
LeetCode 分类刷题:141. 环形链表
javascript·算法·leetcode
初听于你2 小时前
Java五大排序算法详解与实现
数据结构·算法·排序算法
多多*2 小时前
牛客周赛 Round 117 ABCDE 题解
java·开发语言·数据结构·算法·log4j·maven
liu****2 小时前
13.POSIX信号量
linux·开发语言·c++·算法·1024程序员节
熬夜敲代码的小N2 小时前
仓颉ArrayList动态数组源码分析:从底层实现到性能优化
数据结构·python·算法·ai·性能优化
Kt&Rs3 小时前
11.9 LeetCode 题目汇总与解题思路
算法·leetcode