Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Can even calculate the target without bruteforcing. . n^2+n is approximated by n^2 when n is large. Can take the mean of all the distances and use that (or perhaps +/- 1).

    val crabs = lines.first().split(",").map { it.toInt() }
    val avg = crabs.sum() / crabs.size
    return crabs.sumOf { abs(it - avg).let {dst -> (dst * (dst + 1)) / 2} } 
And similarly for part1 take the median. Why it kinda works:

Part1: The median I felt made sense intuitively, as in my head I thought about an example ala 1,1,3,100. Never makes sense to use x>3, because even though the crab at x=100 then can walk shorter, there are 3 others then having to walk longer. And x=1,2or3 doesn't matter, just symmetrically changes which side has to walk one step less or one step more.

And for part2 I thought similar, except the cost is exponential and therefore I want to minimize the avg move and not the total moves, thus taking the average.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: