//Method that will calculate the Max chest it can possibly do. public static long CalculateMaxChest() { long best = 0; for (int i = 0; i < pondCols; i++) { //Create a long list of longs long[] depthList = new long[pondRows]; //for each row in pond rows, calculate depths for (int k = 0; k < pondRows; k++) { depthList[k] = pondMap[k, i]; } for (int j = i; j < i + chestRows && j < pondCols; j++) { long width = (long)(j - i + 1); var maxDimen = chestRows; if (width <= chestRows) { maxDimen = chestCols; } for (int k = 0; k < pondRows; k++) { depthList[k] = Math.Min(depthList[k], pondMap[k, j]); } Stack <StackTuple> s = new Stack <StackTuple>(); for (int k = 0; k < pondRows; k++) { if (s.Count == 0 || depthList[k] > s.Peek().depth) { s.Push(new StackTuple(k, k, depthList[k])); } else { //Make sure we get things that manage to stop here while (s.Count > 0 && depthList[k] <= s.Peek().depth) { StackTuple done = s.Pop(); long tryBest = CalcDisplacement(width * Convert.ToInt64(Math.Min(k - done.start, maxDimen)), done.depth); if (tryBest > best) { best = tryBest; } } if (s.Count == 0) { s.Push(new StackTuple(0, k, depthList[k])); } else if (depthList[k] > s.Peek().depth) { s.Push(new StackTuple(s.Peek().index + 1, k, depthList[k])); } } } //While everything else stops here while (s.Count > 0) { StackTuple done = s.Pop(); long tryBest = CalcDisplacement(width * Convert.ToInt64(Math.Min(pondRows - done.start, maxDimen)), done.depth); if (tryBest > best) { best = tryBest; } } } } return(best); }