solution to overcome TLE -- test case [1,1,1...]


  • 0
    N

    I found after the contest a new test case was added, which fails both all of my accepted solutions during contest and solutions posted in the forum. So I came up with a new solution that can pass this tricky [1,1,1,...] test case.

    class Solution {
        public int numSubarrayProductLessThanK(int[] nums, int k) {
            int ct = 0;
            int prev = -1;          // the last index where prod < k in last iteration
            int pProd = 1;        //  the product from last iteration, which is less than k
          
            for (int i = 0; i < nums.length; i++) {
                
                ct += Math.max(prev-i+1, 0);    // if the product from nums[i-1, prev] is less than k, we are sure the product from nums[i, prev] is also less than k
                
                int prod = prev < i ? 1 : (pProd / nums[i-1]);
                
                for (int j = Math.max(i, prev+1); j < nums.length; j++) {
                    prod *= nums[j];
                    if (prod >= k) {
                        pProd = prod / nums[j];
                        prev = j-1;
                        break;
                    }
                    if (j == nums.length-1) {
                        pProd = prod;
                        prev = j;
                    }
                    ct ++;
                }
            }
            return ct;
            
        }
    }
    

Log in to reply
 

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