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
相关推荐
GISer_Jing7 分钟前
前端算法实战:大小堆原理与应用详解(React中优先队列实现|求前K个最大数/高频元素)
前端·算法·react.js
小森77671 小时前
(三)机器学习---线性回归及其Python实现
人工智能·python·算法·机器学习·回归·线性回归
振鹏Dong2 小时前
超大规模数据场景(思路)——面试高频算法题目
算法·面试
uhakadotcom2 小时前
Python 与 ClickHouse Connect 集成:基础知识和实践
算法·面试·github
uhakadotcom2 小时前
Python 量化计算入门:基础库和实用案例
后端·算法·面试
uhakadotcom2 小时前
使用 Python 与 BigQuery 进行交互:基础知识与实践
算法·面试
uhakadotcom2 小时前
使用 Hadoop MapReduce 和 Bigtable 进行单词统计
算法·面试·github
XYY3693 小时前
前缀和 一维差分和二维差分 差分&差分矩阵
数据结构·c++·算法·前缀和·差分
longlong int3 小时前
【每日算法】Day 16-1:跳表(Skip List)——Redis有序集合的核心实现原理(C++手写实现)
数据库·c++·redis·算法·缓存
24白菜头3 小时前
C和C++(list)的链表初步
c语言·数据结构·c++·笔记·算法·链表