2018年6月3日 星期日

[LeetCode] 713. Subarray Product Less Than K

轉自LeetCode

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.


  • <Solution>

    想法如下
    • 用兩個指標,紀錄目前 subarray 的左邊界和右邊界。如果目前的乘積依然小於 k,那麼右邊界繼續向右動,左邊界不動;若是乘積大於等於 k,那麼將左邊界往右移,並且將乘積除掉剛剛左移的數字
    • 而每次能增加的 subbarray 數目,等於 right - left + 1
    code 如下

    Java(參考解答)


    Kotlin

    沒有留言:

    張貼留言