Skip to content

Instantly share code, notes, and snippets.

@KMNowak
Last active August 19, 2022 12:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KMNowak/21ee69957efb98e8aa76f81f5bd1ae8c to your computer and use it in GitHub Desktop.
Save KMNowak/21ee69957efb98e8aa76f81f5bd1ae8c to your computer and use it in GitHub Desktop.
Solution to 'Mushroom Picker' Codility task with O(n+m) complexity thanks to use of prefix sums. Source: https://codility.com/media/train/3-PrefixSums.pdf
const a = [2,3,7,5,1,3,9]
const startI = 4
const moves = 6
const mushroomPicker = (A, k, m) => {
let maxSum = 0
let sumFromMovesL = 0 // stores prefix sum for each step moving left
for (
let movesL = 0;
k - movesL >= 0 // iterate left until reaching the beginning of an array A
&& movesL <= m; // and do it also as long as we don't use all moves
movesL++
) {
let sumFromMovesR = 0
const currPos = k - movesL // get current position relative to beginning k
sumFromMovesL+= A[currPos] // add current value to already calculated prefix sums of moves to the left
for (
let movesR = 0;
movesR <= m - movesL * 2 // iterate right only if can actually move back to position k (still have enough moves despite reducing them by number of moves left)
&& k + 1 + movesR < A.length; // and if next position is still in the array A
movesR++
) {
const newPos = k + 1 + movesR // get next new position (+1 because we don't want to sum already used position k where we got back)
sumFromMovesR+= A[newPos] // add to existing prefix sum for moves right
}
maxSum = Math.max(maxSum, sumFromMovesL + sumFromMovesR) // simply get the max number from calculated for each scenario sums
}
return maxSum
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment