Created
April 4, 2022 16:39
-
-
Save caglarorhan/bdd90d12d3b40c8bba35ecb556e5d2b8 to your computer and use it in GitHub Desktop.
Using sliding window pattern to find something in an array which has to be a sub array.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let maxSubarraySum = (arr,n)=>{ | |
if(n<1 || n>arr.length){return undefined} | |
let maxSum = -Infinity; | |
let windowSum = arr | |
.filter((item,index)=>index<n) | |
.reduce((sum,item)=>sum+item,0); | |
//console.log('Baslangic ara toplami:', windowSum); | |
for(let x= 0; x<arr.length-n;x++){ | |
windowSum =windowSum-arr[x]+arr[x+n] | |
//console.log('ara toplam:', windowSum) | |
maxSum = Math.max(maxSum,windowSum) | |
} | |
return maxSum; | |
} | |
let arr = [1,2,3,8,4,5,6,7,5,2]; | |
//console.log(maxSubarraySum(arr,3)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment