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

前端 未结 4 1118
执念已碎
执念已碎 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:19

    This is in reference to O(n*c) algo that you mentioned. It's O(n logc) if you look closely.

    A caterpillar eats all multiple of its 'jump step' j, thus if it were alone, each caterpillar would eat floor(n/j) leaves.

    This complexity is bounded by: n+n/2+n/3+...+n/c <= n log(c)

    It won't make a difference as c is small but just pointing out :)

    Check this link for implementation of Inclusion-exclusion by Cimbali: figure out Uneaten Leaves algorithm bug

    EDIT: Here is the proof that the harmonic series is bounded by log(c). We use the inequality for lower limit of integration.

    enter image description here

提交回复
热议问题