713. Subarray Product Less Than K

Link

Solution

想法是找出符合規定的substring,所以將nums依序進行乘積取得production,當production >= K 時縮減 start直到符合結果,反之若production < k,則增加count數

這題要知道幾個技巧才能算。

  1. 首先是每輪增加的count數 會等於 substring的長度

  2. 再來是如何完成當 production >= k時,縮減start將production /= nums[start]

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

Last updated

Was this helpful?