Created
April 18, 2022 23:52
-
-
Save g-bel/776ac1b217b703b69f38004017a68459 to your computer and use it in GitHub Desktop.
Cassidy Williams - question of the week 2021-04-18
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
const largestSubarraySum = (arr, arrLength) => { | |
let highestSubArr = arr.splice(0, arrLength); | |
let tempSubArr = [...highestSubArr]; | |
let total = highestSubArr.reduce((t, c) => t += c, 0); | |
let tempSubArrTotal = total; | |
for (let i = 0; i < arr.length; i++) { | |
let tmp; | |
[tmp, ...tempSubArr] = [...tempSubArr, arr[i]]; | |
tempSubArrTotal = tempSubArrTotal - tmp + arr[i]; | |
if (tempSubArrTotal > total) { | |
highestSubArr = tempSubArr; | |
total = tempSubArrTotal; | |
} | |
} | |
return highestSubArr; | |
}; | |
console.log(largestSubarraySum([3, 1, 4, 1, 5, 9, 2, 6], 3)); | |
console.log(largestSubarraySum([3, 1, 4, 1, 5, 9, 2, 6], 4)); | |
console.log(largestSubarraySum([3, 9, 9, 5, 5, 8, 2, 6], 3)); | |
console.log(largestSubarraySum([8, 9, 9, 6, 5, 8, 2, 6], 3)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment