BudiBadu Logo

Twilight Lantern Garden

Dynamic Programming Hard 0 views
Like14

In Twilight Lantern Garden you process a sequence of energy adjustments and count valid ways to finish with a target charge while never dropping below zero at any step Think of it as constrained path counting through energy states each position updates charge but only non-negative intermediate states are allowed to survive A clean method is dynamic programming over step index and current charge Start from the initial charge state apply each adjustment transition and discard any transition that yields negative energy Aggregate counts for identical resulting charges taking every addition modulo 1 000 000 007 After all petals are processed read the count at exactly the target charge If no states reach it return zero The judge includes cases with immediate invalid drops multiple routes converging to the same charge and empty sequences For empty input the answer is one when target is zero and zero otherwise Return a single integer count only This hard-level task reinforces state-compression thinking legality filtering at transition time and modular counting discipline The core challenge is not raw complexity but maintaining precise state validity so no illegal path leaks into the final total Memory can be optimized with layered maps or arrays that keep only current and next step states since transitions depend on the previous layer only This preserves correctness while reducing footprint which helps when charge ranges widen in larger hidden tests When the task involves connectivity or route cost build

Examples

Example 1
Input
petals = [1,-2], target = 0
Output
0
Explanation

Energy becomes negative after the second petal, so no path is valid.

Example 2
Input
petals = [1,-1,2], target = 2
Output
1
Explanation

The energy sequence is 1,0,2 and never dips below zero.

Example 3
Input
petals = [2,-3,1,2], target = 2
Output
2
Explanation

Two valid sequences maintain nonnegative energy at every step.

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