SR
You can calculate the triangle number of Math.abs(crab - i) instead of summing a range from 1 to Math.abs(crab - i). It would look something like this: var positionCost = crabs.Select(crab = > { var dist = Math.abs(crab - i); return dist * (dist + 1 ) / 2 ; }).Sum(); It gives the same answer and it is a lot faster. I found this out after reading your post. Thanks for posting! It helped a lot!