Caterpillars and Leaves. Can we do better than O(n*c)?

前端 未结 4 1036
执念已碎
执念已碎 2021-02-08 20:59

Found this question while preparing for interviews.

Suppose that some caterpillars start from the bottom and jump to the next leaf. They eat the leaf before jumping to n

4条回答
  •  长发绾君心
    2021-02-08 21:29

    The complexity can't be of O(N) or even O(N/K). My algorithm is of O(2^K), which is huge in itself but still acceptable. Even if I pass N = Long.MAX_VALUE, I get immediate results. Though if K is greater, the code may take time or the code may break when LCM of all jump values exceeds Long.MAX_VALUE.

    To explain it, let's take A = {4, 5, 6} and N = 20.

    We can count uneaten leaves are {1, 2, 3, 7, 9, 11, 13, 14, 17, 19} = 10

    How can we get this result without counting? N - (N / 4) - (N / 5) - (N / 6) + (N / 20) + (N / 12) + (N / 30) - N / 60 = 20 - 5 - 4 - 3 + 1 + 1 + 0 - 0 = 20 - 12 + 2 = 10

    Caterpillar Uneaten Leaves Problem

提交回复
热议问题