Skip to content

Instantly share code, notes, and snippets.

@MichaelWalker-git
Created October 21, 2016 15:51
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 MichaelWalker-git/cbc1fad57f2de7908f7e94cbb2d8c01c to your computer and use it in GitHub Desktop.
Save MichaelWalker-git/cbc1fad57f2de7908f7e94cbb2d8c01c to your computer and use it in GitHub Desktop.
Given non empty, zero indexed array (A)
A has n integers (1 < n < 100000)
A represents number of mushrooms growing in a consecutive spots along the road
Given integers k and m
k = spot on the road and m = number of moves
In one move, she moves to an adjacent spot
Goal: Find maximum number of mushrooms (A[i]) in (m) moves
// Solution #1: Picker doesn't switch more than once
// Time Complexity: O(m^2)
function picker(A, k, m){
var start = k;
var totalMush = A[k];
while(A[k-1] > A[k]){
k--;
totalMush += A[k]
}
k = start;
while(A[start + 1] > A[start]){
totalMush += A[k];
k++;
}
return totalMush;
}
// Solution #2: Prefix Sums
function prefix_sums(A){
n = A.length;
P = A[0] * (n+1);
for(var i = 1; i< n+1; i++){
P[k] = P[k-1] + A[k-1];
}
return P;
}
function mushrooms( A, k, m){
var leng = A.length;
var result = 0;
var pref = prefix_sums(A);
var left_pos, right_pos
var xrange = Math.min(m,k) +1;
for(var i = 0; i< xrange; i++){
left_pos = k-p;
right_pos = Math.min(n-1, Math.max(k, k+m-2*p);
result = Math.max(result, count_total(pref, left_pos, right_pos))
}
var 2ndrange = Math.min(m +1 ,n-k);
for(var j = 0; j< 2ndrange; j++){
right_pos = k+p;
left_pos = Math.max(0, Math.min(k, k-(m-2 *p)))
result = max(result, count_total(pref, left_pos, right_pos))
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment