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
相关推荐
颜酱9 小时前
图结构完全解析:从基础概念到遍历实现
javascript·后端·算法
m0_7369191010 小时前
C++代码风格检查工具
开发语言·c++·算法
yugi98783810 小时前
基于MATLAB强化学习的单智能体与多智能体路径规划算法
算法·matlab
DuHz10 小时前
超宽带脉冲无线电(Ultra Wideband Impulse Radio, UWB)简介
论文阅读·算法·汽车·信息与通信·信号处理
Polaris北极星少女10 小时前
TRSV优化2
算法
代码游侠11 小时前
C语言核心概念复习——网络协议与TCP/IP
linux·运维·服务器·网络·算法
2301_7634724611 小时前
C++20概念(Concepts)入门指南
开发语言·c++·算法
abluckyboy12 小时前
Java 实现求 n 的 n^n 次方的最后一位数字
java·python·算法
园小异12 小时前
2026年技术面试完全指南:从算法到系统设计的实战突破
算法·面试·职场和发展
m0_7066532312 小时前
分布式系统安全通信
开发语言·c++·算法