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
相关推荐
技术炼丹人1 小时前
从RNN为什么长依赖遗忘到注意力机制的解决方案以及并行
人工智能·python·算法
NfN-sh2 小时前
计数组合学7.12( RSK算法的一些推论)
笔记·学习·算法
ikkkkkkkl2 小时前
LeetCode:15.三数之和&&18.四数之和
c++·算法·leetcode
屁股割了还要学2 小时前
【数据结构入门】链表
c语言·开发语言·数据结构·c++·学习·算法·链表
Mr数据杨2 小时前
数据与模型优化随机森林回归进行天气预测
算法·随机森林·回归
chen1113 小时前
有关人工智能(AI)的搜索算法(CS50)
算法
恣艺3 小时前
LeetCode 135:分糖果
算法·leetcode·职场和发展
TDengine (老段)3 小时前
TDengine 中 TDgp 中添加算法模型(异常检测)
java·大数据·数据库·算法·时序数据库·tdengine·涛思数据
2501_924748243 小时前
高密度客流识别精度↑32%!陌讯多模态融合算法在智慧交通的实战解析
大数据·人工智能·算法·目标检测·计算机视觉
WeiJingYu.4 小时前
逻辑回归的应用
算法·机器学习·逻辑回归