Code Logo

Evening Harmony Partition Count

Published at05 Jan 2026
Hard 1 views
Like10

You are given a list of notes and a volume limit. Your job is to split the list into contiguous segments so that the sum of each segment does not go above the limit, then count how many different valid partitions exist.

The segments must stay in the original order, because this is a partition problem, not a subset problem. Every cut changes what the next segment can contain.

For example, if notes = [2,2,2,2] and limit = 4, each segment can contain one or two notes, and that leads to 5 valid partitions. If notes = [5] and limit = 3, the answer is 0 because even the single note is already too large to fit into any valid segment.

So the task is to count all ways to cut the array into segments whose sums each stay within the limit.

Example Input & Output

Example 1
Input
notes = [5], limit = 3
Output
0
Explanation

The single note exceeds the volume limit, so no partition is possible.

Example 2
Input
notes = [2,2,2,2], limit = 4
Output
5
Explanation

Each segment may contain one or two notes, yielding five partitions.

Example 3
Input
notes = [1,2,1], limit = 3
Output
3
Explanation

Valid segmentations are [1|2|1], [1|2,1], and [1,2|1].

Algorithm Flow

Recommendation Algorithm Flow for Evening Harmony Partition Count
Recommendation Algorithm Flow for Evening Harmony Partition Count

Solution Approach

This is a natural prefix dynamic programming problem. Let dp[i] mean the number of valid ways to partition the first i notes.

To compute dp[i], we try every possible place where the last segment could start. Suppose the last segment is notes[j..i-1]. If its sum is at most the limit, then every valid partition of the prefix ending at j can be extended by this segment.

That gives the transition:

dp[i] += dp[j]

for every j where the segment sum from j to i - 1 is valid.

Using prefix sums makes it easy to check any segment sum quickly. Then we fill dp from left to right, starting with dp[0] = 1 for the empty prefix.

The final answer is dp[n]. This works well because every partition can be understood as a valid earlier partition plus one last legal segment.

Best Answers

java
import java.util.*;
class Solution {
    public int count_partitions(int[] nums, int k) {
        long total = 0;
        for (int x : nums) total += x;
        if (total % k != 0) return 0;
        long target = total / k;
        int[] ways = new int[k];
        ways[0] = 1;
        long current = 0;
        for (int i = 0; i < nums.length - 1; i++) {
            current += nums[i];
            for (int j = k - 1; j > 0; j--) {
                if (current == j * target) {
                    ways[j] += ways[j-1];
                }
            }
        }
        return ways[k-1];
    }
}