Dynamic Programming21 sections · 916 units
Open in Course

The Problem

Exactly K constraint

Here's the challenge: find the minimum cost (total penalty from all segments) to partition an array into exactly KK segments, where each segment has a cost (for example, the square of its element sum) and the total cost is the sum of all segment costs.

Without the "exactly KK" constraint, simple DP suffices: dp[i]dp[i] = best cost to partition positions 11 to ii.

But "exactly KK" forces you to track count: dp[i][k]dp[i][k] = best cost using exactly kk segments ending at position ii. With n=50,000n = 50{,}000 and K=5,000K = 5{,}000, that's 250250 million states. The extra dimension comes from the constraint. What If could remove the constraint and get the right answer?