C++ O(n) two-pointer concise solution


  • 1
    E
    class Solution {
    public:
        int numSubarrayProductLessThanK(vector<int>& a, int k) {
            int p = 1, j = 0, ans = 0;
            for (int i = 0; i < a.size(); ++i) {
                while (j < a.size() && p * a[j] < k) p *= a[j++];
                ans += j-i;
                if (i == j) ++j, p = 1;
                else p/=a[i];
            }
            
            return ans;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.