zoukankan      html  css  js  c++  java
  • 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.

    Approach #1. Math. [Java]

    class Solution {
        public int numSubarrayProductLessThanK(int[] nums, int k) {
            int pro = 1;
            int cnt = 0;
            
            for (int i = 0, j = 0; j < nums.length; ++j) {
                pro *= nums[j];
                while (i <= j && pro >= k) {
                    pro /= nums[i++];
                }
                cnt += j - i + 1;
            }
            
            return cnt;
        }
    }
    

      

    Analysis:

    The idea is always keep an max-product-window less than K;

    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), untill the subarray product fit less than K again, (subarray could be empty);

    Each step introduces x new  subarrays, where x is the size of the current window (j - i + 1);

    Example:

    for window (5, 2), when 6 is ntroduced, it add 3 new subarray: (5, (2, (6)))

    Reference:

    https://leetcode.com/problems/subarray-product-less-than-k/discuss/108861/JavaC%2B%2B-Clean-Code-with-Explanation

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    读取IIS用户名和密码VBS代码
    sqltools最新增强版
    网站后台备份自动备份成ASA格式却并不表示拿Shell方法
    Google Hack 最新版
    FZU 2105 Digits Count(AC)
    ZOJ 1387 Decoding Morse Sequences
    ZOJ 1391 Horizontally Visible Segments
    codeforces Round #184 Div.2 B Continued Fractions
    FZU 2105 Digits Count(WA)
    POJ 2828 Buy Tickets
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10658785.html
Copyright © 2011-2022 走看看