Skip to content

Instantly share code, notes, and snippets.

@caglarorhan
Created April 4, 2022 16:39
Show Gist options
  • Save caglarorhan/bdd90d12d3b40c8bba35ecb556e5d2b8 to your computer and use it in GitHub Desktop.
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.
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