LeetCode Subarray Product Less Than K
Posted Dylan_Java_NYC
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode Subarray Product Less Than K相关的知识,希望对你有一定的参考价值。
原题链接在这里:https://leetcode.com/problems/subarray-product-less-than-k/description/
题目:
Your are given an array of positive integers nums
.
Count and print the number of (contiguous) subarrays where the product of all the elements in the subarray is 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.
Note:
0 < nums.length <= 50000
.0 < nums[i] < 1000
.0 <= k < 10^6
.
题解:
都是正数, 所以乘积prod是递增的.
使用sliding window, sliding window prod小于k时右侧前进, 大于等于k时左侧前进.
维护计数. 右侧减左侧加一 表示以当前右侧为尾的subarray个数.
Time Complexity: O(nums.length).
Space: O(1).
AC Java:
1 class Solution { 2 public int numSubarrayProductLessThanK(int[] nums, int k) { 3 if(nums == null || nums.length == 0 || k <= 1){ 4 return 0; 5 } 6 7 int res = 0; 8 int prod = 1; 9 int l = 0; 10 int r = 0; 11 while(r < nums.length){ 12 prod *= nums[r]; 13 while(prod >= k){ 14 prod /= nums[l++]; 15 } 16 res += r-l+1; 17 r++; 18 } 19 20 return res; 21 } 22 }
以上是关于LeetCode Subarray Product Less Than K的主要内容,如果未能解决你的问题,请参考以下文章
leetcode 152. Maximum Product Subarray
C#解leetcode 152. Maximum Product Subarray
Maximum Product Subarray Leetcode
[动态规划] leetcode 152 Maximum Product Subarray