[Leetcode 713] Subarray Product Less Than K (medium)

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.

Solution

  • 因为已知所有的数都是positive integers,且要求得到连续的子序列。那么可以用Two Pointer来得到一个子序列。
  • 当当前子序列(left ~ right)的所有数的乘积满足条件,即product < k时,那么可以得到left - right之间,就有right - left + 1个子序列满足条件; 然后向右移动right pointer,继续找子序列。
  • 当当前子序列不满足条件,product >= k时,向右移动left pointer,从而使子序列的乘积变小,看是否能够满足条件。
  • 例如题目,[10, 5, 2, 6],
    left - right : 满足的子序列/ 个数
    [10]: [10] / 1
    [10, 5]: [10, 5], [5] / 2
    [5, 2]: [5, 2], [2] / 2
    [5, 2, 6] : [5, 2, 6], [2, 6], [6] / 3
    所以总个数为 1 + 2 + 2 + 3 = 8
class Solution {
    public int numSubarrayProductLessThanK(int[] nums, int k) {
        int product = 1;
        int result  = 0;
        int left    = 0;
        int right   = 0;
        
        for (; right < nums.length; right ++)
        {
            product *= nums [right];
            
            while (left <= right && product >= k)
            {
                product = product / nums [left];
                left ++;
            }
            
            result += right - left + 1;
        }
        
        return result;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容