[Solved] Planting Trees

In a particular field, there are trees in a single row from left to right. Each tree has a value V. You cut trees from left to right and for each tree of value V that you cut, you plant (V+ 1) % M trees on the right most end with values ranging from 0 to ((V+1) % M) – 1.

Initially, there was only one tree with value 2. Find the total number of trees present after cutting K trees.

Input Specification:

input1: K, denoting the number of trees that are cut.

input2: M, denoting the modulus value.

Output Specification:

Your function should return the total number of trees in the field.

Example 1:

input1: 1

input2: 5

output: 3

Explanation: After cutting the tree with value 2, you have to plant (2+1) %5=3 trees

from 0 to 2

Final field view: (0, 1, 2).

Example 2:

input1: 1

input2: 2

output: 1

Explanation: After cutting the tree with value 2, you have to plant (2+1)%2=1 trees

from 0 to 0.

Final field view: (0).

Solution

public static int totalTrees(int input1, int input2) {

    int totalTrees = 0;
    int[] trees = new int[input1 + 1];
    trees[0] = 2;
    for (int i = 1; i <= input1; i++) {
        int value = trees[i - 1];
        int newTrees = (value + 1) % input2;
        totalTrees += newTrees;
        trees[i] = newTrees;
    }
    return totalTrees;

}

Happy Learning – If you require any further information, feel free to contact me.

Share your love
Saurav Hathi

Saurav Hathi

I'm currently studying Bachelor of Computer Science at Lovely Professional University in Punjab.

📌 Nodejs and Android 😎
📌 Java

Articles: 444

Leave a Reply

Your email address will not be published. Required fields are marked *