Let be the optimal state using the first sticks: maximize boxes , then minimize used sticks . Leaving stick unused gives . If the last box is the segment , it requires prefix sums and gives . For a fixed last box the preceding prefix must be optimal, so this recurrence covers every solution. Subtask 1 checks every in time. For the full task, positive weights make prefix sums increasing. The indices satisfying become eligible in order; a pointer adds each once. Keep the eligible state maximizing and, among ties, minimizing . Compare its candidate with at every position. Time is and space is .
Solution written by GPT6.1