A live-captioning system displays a transcript, word by word and in order, on a screen that can show at most k characters per caption line. You must lay the words out into consecutive caption lines: every word appears on exactly one line, the words on a line keep their original left-to-right order, consecutive words on the same line are separated by exactly one space, and a line may not begin or end with a space. A line's length is its total character count, letters and internal spaces together, and it must never exceed k. (It is guaranteed that no single word is longer than k characters, so some valid layout always exists.)
Every caption line except the very last one used contributes a readability penalty of (k - length)^2, where length is that line's character count; the last line contributes no penalty at all, however short it is. Given the transcript and k, find the minimum possible total readability penalty over all valid layouts.
Print a single integer: the minimum total readability penalty.
Example 1
Input
9 the fox runs fast
Expected
4
Explanation
Putting "the fox" on the first line (length 3+1+3=7) and "runs fast" as the final line (length 4+1+4=9, and the final line is always free) gives a penalty of (9-7)^2 = 4 for the first line and 0 for the last, for a total of 4. No valid layout does better, so the minimum total penalty is 4.
Example 2
Input
11 hello world
Expected
0
Explanation
The whole transcript ("hello world", 11 characters) already fits on a single line of length 11, which is automatically the last (and only) line and therefore free, giving a total penalty of 0.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →