713. Subarray Product Less Than K

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.
  • Rust Solution

    struct Solution;
    
    impl Solution {
        fn num_subarray_product_less_than_k(nums: Vec<i32>, k: i32) -> i32 {
            let n = nums.len();
            let mut i = 0;
            let mut product = 1;
            let mut res = 0;
            for j in 0..n {
                product *= nums[j];
                while i <= j && product >= k {
                    product /= nums[i];
                    i += 1;
                }
                res += (j + 1 - i) as i32;
            }
            res
        }
    }
    
    #[test]
    fn test() {
        let nums = vec![10, 5, 2, 6];
        let k = 100;
        let res = 8;
        assert_eq!(Solution::num_subarray_product_less_than_k(nums, k), res);
        let nums = vec![1, 2, 3];
        let k = 0;
        let res = 0;
        assert_eq!(Solution::num_subarray_product_less_than_k(nums, k), res);
        let nums = vec![1, 1, 1];
        let k = 1;
        let res = 0;
        assert_eq!(Solution::num_subarray_product_less_than_k(nums, k), res);
    }
    

    Having problems with this solution? Click here to submit an issue on github.