Skip to content

Instantly share code, notes, and snippets.

@VegaFromLyra
Created July 10, 2015 16:52
Show Gist options
  • Save VegaFromLyra/2927c4a93434130e65dc to your computer and use it in GitHub Desktop.
Save VegaFromLyra/2927c4a93434130e65dc to your computer and use it in GitHub Desktop.
Mushroom picker
using System;
// https://codility.com/media/train/3-PrefixSums.pdf
namespace MushroomPicker
{
public class Program
{
public static void Main(string[] args)
{
// int[] A = {2, 3, 7, 5, 1, 3, 9};
// int k = 4;
// int m = 6;
int[] A = {3, 2, 5, 1, 6, 11};
int k = 3;
int m = 4;
var maxMushrooms = maximumMushrooms(A, k, m);
Console.WriteLine("Maximum number of mushrooms is {0}", maxMushrooms);
}
// Time : O(n ^ 2)
// Space: O(n * m)
static int maximumMushrooms(int[] A, int k, int m) {
int maxSum = 0;
for (int p = 0; p <= m; p++) {
bool[] visited = new bool[A.Length];
int currentSum = A[k];
visited[k] = true;
int leftMoves = p;
for(int i = k, count = 0; (i - 1) >= 0 && count < leftMoves; i--, count++) {
currentSum += A[i - 1];
visited[i - 1] = true;
}
int rightMoves = m - p;
for(int i = k - p, count = 0; (i + 1) < A.Length && count < rightMoves; i++, count++) {
if (!visited[i + 1]) {
currentSum += A[i + 1];
}
}
if (currentSum > maxSum) {
maxSum = currentSum;
}
}
return maxSum;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment