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
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