Wednesday, October 25, 2017

713. Subarray Product Less Than K

https://leetcode.com/problems/subarray-product-less-than-k/description/
Solution 1. Count from 0 to i
    int numSubarrayProductLessThanK(vector<int>& nums, int k) {
        if(k==0) return 0;
        int res = 0, N = nums.size();
        for(int i=0, j=0, s=1; i<N; i++) {
            s *= nums[i];
            while(j <= i && s>=k) s /= nums[j++];
            res += i-j+1;
        }
        return res;
    }
Solution 2. Count from i to N
    int numSubarrayProductLessThanK(vector<int>& nums, int k) {
        if(k==0) return 0;
        int res = 0, N = nums.size();
        for(int i=0, j=0, s=1; i<N; i++) {
            if(i > 0 && i <= j) s /= nums[i-1];
            else j = i;
            while(j<N && s*nums[j]<k) s *= nums[j++];
            res += j-i;
        }
        return res;
    }

No comments:

Post a Comment