Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit ca5d2a4

Browse files
author
Swastikyadav
committed
Create a folder for sliding window patterns
1 parent c92b8e9 commit ca5d2a4

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

‎Algo-Patterns/sliding-window.js renamed to ‎Algo-Patterns/sliding-window-pattern/01-max-sum-of-contiguous-subarray.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,4 +32,7 @@ function maximumSumSubArrayofK(arr, k) {
3232

3333
console.log(maximumSumSubArrayofK([7, 43, 4, 6, 8, 11, 2], 3));
3434
console.log(maximumSumSubArrayofK([2, 1, 5, 1, 3, 2], 3));
35-
console.log(maximumSumSubArrayofK([2, 3, 4, 1, 5], 2));
35+
console.log(maximumSumSubArrayofK([2, 3, 4, 1, 5], 2));
36+
37+
// Time Complexity - O(n)
38+
// Space Complexity - O(1)
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/*
2+
This problem follows the Sliding Window pattern and we can use a similar strategy as discussed in previous question. There is one difference though: in this problem, the size of the sliding window is not fixed. Here is how we will solve this problem:
3+
4+
Given an array of positive numbers and a positive number ‘S’, find the length of the smallest contiguous subarray whose sum is greater than or equal to ‘S’. Return 0, if no such subarray exists.
5+
6+
Examples:
7+
Input: [2, 1, 5, 2, 3, 2], S=7
8+
Output: 2
9+
*/
10+
11+
function smallest_sub_array_with_given_sum(arr, s) {
12+
let start = 0;
13+
let windowSum = 0;
14+
let minLength = Infinity;
15+
16+
for (let end = 0; end < arr.length; end++) {
17+
windowSum += arr[end];
18+
19+
while(windowSum >= s) {
20+
minLength = Math.min(minLength, end - start + 1);
21+
windowSum -= arr[start];
22+
start++;
23+
}
24+
}
25+
26+
return minLength;
27+
}
28+
29+
console.log(smallest_sub_array_with_given_sum([2, 1, 5, 2, 3, 2], 7));
30+
console.log(smallest_sub_array_with_given_sum([2, 1, 5, 2, 8], 7));
31+
console.log(smallest_sub_array_with_given_sum([3, 4, 1, 1, 6], 8));
32+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /