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
相关推荐
geovindu3 小时前
python:DecisionTree
开发语言·后端·python·算法
geovindu4 小时前
python: Decision Tree Regressor
开发语言·后端·python·算法·决策树
AllData公司负责人7 小时前
实战二:AllData大模型与AI数据底座-数据传输平台-DBSyncer,搭建 Http 接口同步至 Doris,API 业务数据自动拉取入数仓
大数据·数据库·数据仓库·人工智能·算法·http·doris
武子康7 小时前
火系被选七成,就应该削弱吗?
人工智能·算法·机器学习
夜不会漫长8 小时前
C++:C++11特性
开发语言·c++·算法
秋天的怀念_David9 小时前
算法一千零一夜 · 第三十七夜 · 类型的过路费
java·程序人生·算法
xckkcxxck11 小时前
Kaggle S6E10 冠军方案精读(二):245 个模型的合唱团,和一个只会“线性指挥“的老师
算法
饮水桶_T12 小时前
Git笔记
开发语言·笔记·算法
指掀涛澜天下惊12 小时前
强化学习进阶篇十四 DPO算法
深度学习·算法·机器学习·sft·预训练·dpo