|
| 1 | +/** |
| 2 | +* Sliding Window: |
| 3 | +* This pattern involve creating a window which can either be |
| 4 | +* an array or numbers from one position to another. |
| 5 | +* |
| 6 | +* Depending on a certain condition, the window either increases |
| 7 | +* or closes (and a new window is created). |
| 8 | +* |
| 9 | +* Very useful for keeping track of a subset of data in an |
| 10 | +* array/string etc. |
| 11 | +* |
| 12 | +* Time Complexity: Best - O(n); |
| 13 | +* |
| 14 | +* Examples: |
| 15 | +* maxSubarraySum([1,2,5,2,8,1,5],2) // returns 10 |
| 16 | +* maxSubarraySum([1,2,5,2,8,1,5],15) // returns null |
| 17 | +* maxSubarraySum([5,2,6,9],3) // returns 17 |
| 18 | + * @param {[Int]} arr - An array of integers on which we will perform the test. |
| 19 | + * @param {Int} num - An integer that displays the size of the window you want to check. |
| 20 | + * @returns {Int / Null} - Returns a total of N consecutive numbers or null |
| 21 | + */ |
| 22 | + |
| 23 | +function slidingWindow (arr, num) { |
| 24 | + // Edge Case: |
| 25 | + // If the length of the array shorter than the window size (num) return null. |
| 26 | + if (arr.length < num) return null |
| 27 | + // The highest amount of consecutive numbers |
| 28 | + let maxSum = 0 |
| 29 | + // Temp amount of consecutive numbers - For comparative purposes |
| 30 | + let tempSum = 0 |
| 31 | + // loop over the array {num} times and save their total amount in {maxSum} |
| 32 | + for (let i = 0; i < num; i++) { |
| 33 | + maxSum += arr[i] |
| 34 | + } |
| 35 | + // initialize {tempSum} to {maxSum}. |
| 36 | + tempSum = maxSum |
| 37 | + // loop over the array n times |
| 38 | + for (let i = num; i < arr.length; i++) { |
| 39 | + // Add the next num in the array and remove the first one |
| 40 | + tempSum = tempSum - arr[i - num] + arr[i] |
| 41 | + // save the largest number between {maxNum} and {tempNum} in maxSum. |
| 42 | + maxSum = Math.max(maxSum, tempSum) |
| 43 | + } |
| 44 | + return maxSum |
| 45 | +} |
| 46 | + |
| 47 | +export { slidingWindow } |
0 commit comments