简体   繁体   中英

What should be passed as "tree" when returning the treeHelper method in pickTrees?

Here is the question: you build homes out of wood and you need material from a nearby forest. however, you want to avoid deforestation, so you decide for each tree you cut down, you'll leave its neighbors alone, giving the forest time to recover. however, you still need as much wood as possible, so you have to be careful about which trees you pick to cut down. write picktrees, which takes in an array of n trees arr where arr[i] represents how much wood you can harvest by cutting down tree i. it should return the max amount of wood you can harvest while following the rule of skipping neighbors:

here is my code so far

public static int pickTrees(int[] arr) {
    return treeHelper(arr, ?);
}

public static int treeHelper(int[] arr, int tree){
    if (arr.length < tree){
        return 0;
    }
    if ((arr.length)-1 == tree){
        return 1;
    }
    int sum = arr[tree]+treeHelper(arr, tree+2);

    int otherSum = arr[tree+1]+treeHelper(arr, tree+3);

    return Math.max(sum, otherSum);

}

Tree is supposed to be the index of the array that is being "cut down" and added to the variables sum and other sum. Because I define it in the treeHelper method, when using it in the pickTrees method, I am unsure what should be passed as tree. When I used arr.length, I got an out of bounds error, which makes sense because the base cases will never be true/reached.

Try passing Set of Integer pickedTrees as the second parameter treeHelper.

Try continuing from here, first try to understand what the treeHelper return value should mean.

(I'm answering with a hint and not the full solution because I think learning by doing is the best kind of learning)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM