Member-only story
Go solution to Leetcode 1006 Clumsy Factorial
In this Leetcode problem, we are asked to compute clumsy(N) = N * (N-1) / (N-2) + (N-3) — (N-4) * (N-5) / (N-6) + (N-7) ...
(stopping when we reach 1
), respecting the operations priorities (*
and /
before +
and -
).
One thing to notice for the recursion is that it is curious that N doesn’t have a minus sing in front, and the series goes (+) * / + — * / + -
instead of the more natural — * / + — * / + -
.
So I used the trick to actually compute- N* (N-1) / (N-2) + (N-3) — (N-4) * (N-5) / (N-6) + (N-7) ...
and at the end I added the required:2*(N(N-1)/(N-2))
.
There isn’t much more than that for the recursion. Here is the code. It runs in 0ms
beating 100%
of answers.
func clumsy(N int) int {
if N == 1 {
return 1
}
if N == 2 {
return 2
}
if N == 3 {
return 6
}
if N == 4 {
return 7
}
return 2*(N*(N-1)/(N-2)) + clumsyRec(N)
}func clumsyRec(N int) int {
if N == 1 {
return -1
}
if N == 2 {
return -2
}
if N == 3 {
return -6
}
if N == 4 {
return -5
}
return - N*(N-1)/(N-2) + (N-3) + clumsyRec(N-4)
}
Hope it helped, happy coding!