Loading…
Loading…
A dormouse is wrapping the cellar shelves for the holidays. One ribbon around a shelf takes in that shelf and every descendant below it. She has a voucher for any such bundle holding between lower and upper units of stock, both ends included. Given stock[i] on each shelf, return the number of shelves she could tie her ribbon around. Count each choice, including one tucked inside another. The shelves form a tree rooted at shelf 0, with parent[0] = -1. Every other parent[i] names the parent of shelf i, which can have a larger index than its child.
[-1,0,0,1], [2,3,5,7], 7, 10Output2The branch of shelf 1 holds 3 + 7 = 10 and the branch of shelf 3 holds 7. The other two totals, 17 and 5, fall outside the range.
[-1,0,1], [0,0,0], 0, 0Output3All three branch totals are zero, so all three shelves count, even though the branches lie inside one another.
A branch total is the shelf's own stock plus the branch totals of its children, so each child has to be finished before its parent.
/** @param {number[]} parent * @param {number[]} stock * @param {number} lower * @param {number} upper * @returns {number} */ function solve(parent, stock, lower, upper) { // Count the shelves whose branch total is in range. }
Tab inserts two spaces. Shift+Tab outdents. Use the arrow keys and Tab to choose a suggestion. Press Escape, then Tab, to leave the editor. Press Control or Command with apostrophe to run samples or with Enter to submit.