Skip to the code
cf.
+50 XP

#550 Wrap Text With the Least Ragged Edge

hard

A canvas-based text editor lays out a paragraph whose word lengths are wordLengths, in order, into lines at most width characters wide. Words on the same line are separated by one space, and words can't be split or reordered.

A line with extra unused characters at its end costs extra * extra, except the last line, which is free. Write leastRaggedCost(wordLengths, width) that returns the smallest total cost of a layout. Every word fits on a line by itself.

Example 1

Input: wordLengths = [3,2,2,5], width = 6
Output: 10

Lines of lengths 3 (3 extra), 2 + 1 + 2 = 5 (1 extra), and the last line 5: 9 + 1 = 10. Filling the first line greedily (3 + 1 + 2 = 6) leaves a line of just 2 and costs 16.

Example 2

Input: wordLengths = [4], width = 4
Output: 0

A single line is the last line, which is free.

Constraints

  • 1 <= wordLengths.length <= 500
  • 1 <= wordLengths[i] <= width <= 100
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).