Leetcode - The K Weakest Rows in a Matrix
Leetcode - subarray-sums-divisible-by-k

Leetcode - subarray-product-less-than-k

violet posted @ Feb 27, 2020 05:32:23 AM in 算法 with tags Algorithm array Golang , 332 阅读

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.
  1. The idea is always to keep an max-product-window less than K;
  2. Every time shift window by adding a new number on the right(j), if the product is greater than k, then try to reduce numbers on the left(i), until the subarray product fit less than k again, (subarray could be empty);
  3. Each step introduces x new subarrays, where x is the size of the current window (j + 1 - i);
    example:
    for window (5, 2), when 6 is introduced, it adds 3 new subarrays: (5, (2, (6)))
        (6)
     (2, 6)
  (5, 2, 6)
func numSubarrayProductLessThanK(nums []int, k int) int {
    if k == 0 {
        return 0
    }
    count := 0
    product := 1
    i := 0
    j := 0
    for j < len(nums) {
        product *= nums[j]
        for i <= j && product >= k {
            product /= nums[i]
            i++
        }
        count += j - i + 1
        j++
    }
    return count
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter