Code Logo

Twilight Lantern Garden

Published at05 Jan 2026
Hard 1 views
Like14

This problem is about counting valid petal sequences that end at exactly the target energy, with one extra safety rule: the running energy is never allowed to drop below zero at any point along the way.

That nonnegative prefix condition is the part that makes the problem more than a normal target-sum count. A sequence might end at the right target but still be invalid if it dips below zero in the middle.

For example, if petals = [1,-2] and target = 0, the answer is 0 because the running energy becomes negative. If petals = [1,-1,2] and target = 2, the answer is 1 because the valid energy trail stays at 1, then 0, then 2.

So the task is to count all valid sequences that reach the target while keeping every intermediate energy value nonnegative.

Example Input & Output

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
Recommendation Algorithm Flow for Twilight Lantern Garden

Solution Approach

This kind of problem is easiest to handle with memoized recursion or DP on state. The useful state is the current position in the petal process together with the current energy value.

A state can be written like:

dp(index, energy)

From there, we explore the allowed next continuation. Any branch that makes energy negative can be rejected immediately, because it can never become valid again. When we reach the end, we count the branch only if the final energy is exactly the target.

The reason memoization helps is that the same pair of (index, energy) can appear through different partial choices. Once we know how many valid completions come from that state, we can reuse it instead of recomputing the whole subtree.

So the core idea is: track where you are, track the current energy, stop early on negative states, and cache repeated states. That turns an exponential search into a manageable dynamic programming solution.

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