Evening Harmony Partition Count
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
The single note exceeds the volume limit, so no partition is possible.
Each segment may contain one or two notes, yielding five partitions.
Valid segmentations are [1|2|1], [1|2,1], and [1,2|1].
Algorithm Flow

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:
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
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];
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
