JavaScript 中乘積剛好小於目標值的子陣列


問題

我們需要編寫一個 JavaScript 函式,該函式將第一個引數視為數字陣列 arr,第二個引數視為數字 target。

我們的函式應該統計和返回(連續)子陣列的數量,其中子陣列中所有元素的乘積小於目標值。

例如,如果函式的輸入是

輸入

const arr = [10, 5, 2, 6];
const target = 100;

輸出

const output = 8;

輸出解釋

乘積小於 100 的 8 個子陣列是 −

[10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6].

請注意,[10, 5, 2] 沒有包括在內,因為 100 的乘積不嚴格小於 k。

示例

以下是程式碼 −

 線上演示

const arr = [10, 5, 2, 6];
const target = 100;
const countSubarrays = (arr = [], target = 1) => {
   let product = 1
   let left = 0
   let count = 0
   for (let right = 0; right < arr.length; right++) {
      product *= arr[right]
      while (left <= right && product >= target) {
         product /= arr[left]
         left += 1
      }
      count += right - left + 1
   }
   return count
};
console.log(countSubarrays(arr, target));

輸出

8

更新於: 24-4 月-2021

123 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.