BudiBadu Logo

Twilight Lantern Garden

Dynamic Programming Hard 0 views
Like14

The twilight garden blooms with lantern petals arranged in a linear path. Each petal grants or consumes a small number of energy tokens. Starting with zero energy, gardeners step from the first petal to the last, and after each step the total energy must remain nonnegative; once they reach the final petal their energy should exactly equal the target fireworks charge. The gardeners want to know how many sequences of petals they can walk through while obeying these energy constraints.

You receive the petal adjustments as an array of integers, where each value is added to the current energy upon stepping on that petal. The gardener must step on every petal in order (no skips), and the energy after the final petal must equal the given target. If at any point the energy becomes negative, the path is invalid. Return the number of valid paths modulo 1_000_000_007. Construct your answer via dynamic programming without altering the input arrays, and treat an empty petal list as having zero paths unless the target is also zero, which counts as one.

Example 1:

Input: petals = [1,-1,2], target = 2
Output: 1
Explanation: The energy sequence is 1,0,2 and never dips below zero.

Example 2:

Input: petals = [2,-3,1,2], target = 2
Output: 2
Explanation: Two valid sequences maintain nonnegative energy at every step.

Example 3:

Input: petals = [1,-2], target = 0
Output: 0
Explanation: Energy becomes negative after the second petal, so no path is valid.

Algorithm Flow

Recommendation Algorithm Flow for Twilight Lantern Garden - Budibadu
Recommendation Algorithm Flow for Twilight Lantern Garden - Budibadu

Best Answers

java
class Solution {
    public int count_valid_petal_sequences(int[] petals, int target) {
        if (petals.length == 0) return target == 0 ? 1 : 0;
        int energy = 0;
        for (int p : petals) {
            energy += p;
            if (energy < 0) return 0;
        }
        return energy == target ? 1 : 0;
    }
}