[leetcode] 713. Subarray Product Less Than K

2022-12-24,,

题目

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

思路

双指针,左右指针框起来的数字需要保持积小于k,并在遍历nums的过程中不断地记录数量。

代码

python版本:

class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
cnt, prod, l = 0, 1, 0
for r in range(len(nums)):
prod *= nums[r]
while prod >= k and l <= r:
prod /= nums[l]
l += 1
cnt += r-l+1
return cnt

[leetcode] 713. Subarray Product Less Than K的相关教程结束。

《[leetcode] 713. Subarray Product Less Than K.doc》

下载本文的Word格式文档,以方便收藏与打印。