Skip to content

Commit 3cae80e

Browse files
authored
chore: merge "repulling all together (#694)"
* Create slidingWindow.js * Rename slidingWindow.js to SlidingWindow.js * update the commit
1 parent 3235949 commit 3cae80e

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

Search/SlidingWindow.js

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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 }

Search/test/SlidingWindow.test.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { slidingWindow } from '../SlidingWindow'
2+
3+
test('expect to return the largest sum of sequence in the array', () => {
4+
const sum = slidingWindow([1, 2, 5, 2, 8, 1, 5], 2)
5+
expect(sum).toBe(10)
6+
})
7+
8+
test('expect to return the largest sum of sequence in the array', () => {
9+
const sum = slidingWindow([5, 2, 6, 9], 3)
10+
expect(sum).toBe(17)
11+
})
12+
13+
test('expect to return null when the sequence size is larger then the array length', () => {
14+
const sum = slidingWindow([1, 2, 5, 2, 8, 1, 5], 15)
15+
expect(sum).toBe(null)
16+
})

0 commit comments

Comments
 (0)