Skip to content

Commit

Permalink
chore: merge "repulling all together (TheAlgorithms#694)"
Browse files Browse the repository at this point in the history
* Create slidingWindow.js

* Rename slidingWindow.js to SlidingWindow.js

* update the commit
  • Loading branch information
morMBen authored Sep 22, 2021
1 parent 3235949 commit 3cae80e
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
47 changes: 47 additions & 0 deletions Search/SlidingWindow.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/**
* Sliding Window:
* This pattern involve creating a window which can either be
* an array or numbers from one position to another.
*
* Depending on a certain condition, the window either increases
* or closes (and a new window is created).
*
* Very useful for keeping track of a subset of data in an
* array/string etc.
*
* Time Complexity: Best - O(n);
*
* Examples:
* maxSubarraySum([1,2,5,2,8,1,5],2) // returns 10
* maxSubarraySum([1,2,5,2,8,1,5],15) // returns null
* maxSubarraySum([5,2,6,9],3) // returns 17
* @param {[Int]} arr - An array of integers on which we will perform the test.
* @param {Int} num - An integer that displays the size of the window you want to check.
* @returns {Int / Null} - Returns a total of N consecutive numbers or null
*/

function slidingWindow (arr, num) {
// Edge Case:
// If the length of the array shorter than the window size (num) return null.
if (arr.length < num) return null
// The highest amount of consecutive numbers
let maxSum = 0
// Temp amount of consecutive numbers - For comparative purposes
let tempSum = 0
// loop over the array {num} times and save their total amount in {maxSum}
for (let i = 0; i < num; i++) {
maxSum += arr[i]
}
// initialize {tempSum} to {maxSum}.
tempSum = maxSum
// loop over the array n times
for (let i = num; i < arr.length; i++) {
// Add the next num in the array and remove the first one
tempSum = tempSum - arr[i - num] + arr[i]
// save the largest number between {maxNum} and {tempNum} in maxSum.
maxSum = Math.max(maxSum, tempSum)
}
return maxSum
}

export { slidingWindow }
16 changes: 16 additions & 0 deletions Search/test/SlidingWindow.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { slidingWindow } from '../SlidingWindow'

test('expect to return the largest sum of sequence in the array', () => {
const sum = slidingWindow([1, 2, 5, 2, 8, 1, 5], 2)
expect(sum).toBe(10)
})

test('expect to return the largest sum of sequence in the array', () => {
const sum = slidingWindow([5, 2, 6, 9], 3)
expect(sum).toBe(17)
})

test('expect to return null when the sequence size is larger then the array length', () => {
const sum = slidingWindow([1, 2, 5, 2, 8, 1, 5], 15)
expect(sum).toBe(null)
})

0 comments on commit 3cae80e

Please sign in to comment.