mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2026-03-13 15:21:15 +08:00
Implement sliding window algorithms for fixed and dynamic sizes with tests (#1765)
* feat: implement sliding window algorithms for fixed and dynamic sizes with tests * update directory file for sliding windows
This commit is contained in:
24
Sliding-Windows/test/LongestSubarrayWithSumAtMost.test.js
Normal file
24
Sliding-Windows/test/LongestSubarrayWithSumAtMost.test.js
Normal file
@@ -0,0 +1,24 @@
|
||||
import { longestSubarrayWithSumAtMost } from '../LongestSubarrayWithSumAtMost'
|
||||
|
||||
describe('Dynamic-size Sliding Window - longestSubarrayWithSumAtMost', () => {
|
||||
it('should return the longest subarray length with sum <= target', () => {
|
||||
const arr = [1, 2, 3, 4, 5]
|
||||
const target = 7
|
||||
const result = longestSubarrayWithSumAtMost(arr, target)
|
||||
expect(result).toBe(3)
|
||||
})
|
||||
|
||||
it('should return the full array length if the entire sum is within the target', () => {
|
||||
const arr = [1, 1, 1, 1]
|
||||
const target = 4
|
||||
const result = longestSubarrayWithSumAtMost(arr, target)
|
||||
expect(result).toBe(4)
|
||||
})
|
||||
|
||||
it('should return 0 if no subarray meets the sum condition', () => {
|
||||
const arr = [5, 6, 7]
|
||||
const target = 3
|
||||
const result = longestSubarrayWithSumAtMost(arr, target)
|
||||
expect(result).toBe(0)
|
||||
})
|
||||
})
|
||||
22
Sliding-Windows/test/MaxSumSubarrayFixed.test.js
Normal file
22
Sliding-Windows/test/MaxSumSubarrayFixed.test.js
Normal file
@@ -0,0 +1,22 @@
|
||||
import { maxSumSubarrayFixed } from '../MaxSumSubarrayFixed'
|
||||
|
||||
describe('Fixed-size Sliding Window - maxSumSubarrayFixed', () => {
|
||||
it('should return the maximum sum of a subarray of size k', () => {
|
||||
const arr = [2, 1, 5, 1, 3, 2]
|
||||
const k = 3
|
||||
const result = maxSumSubarrayFixed(arr, k)
|
||||
expect(result).toBe(9)
|
||||
})
|
||||
|
||||
it('should throw a RangeError if k is larger than the array length', () => {
|
||||
const arr = [2, 1, 5]
|
||||
const k = 4
|
||||
expect(() => maxSumSubarrayFixed(arr, k)).toThrow(RangeError)
|
||||
})
|
||||
|
||||
it('should throw a RangeError if k is less than 1', () => {
|
||||
const arr = [2, 1, 5]
|
||||
const k = 0
|
||||
expect(() => maxSumSubarrayFixed(arr, k)).toThrow(RangeError)
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user