![]() |
VOOZH | about |
Given an array arr[] of size n, where arr[i] denotes the number of characters in one word. Let k be the limit on the number of characters that can be put in one line (line width). Put line breaks in the given sequence such that the lines are printed neatly.
Assume that the length of each word is smaller than the line width. When line breaks are inserted there is a possibility that extra spaces are present in each line. The extra spaces include spaces put at the end of every line except the last one.
The task is to minimize the following total cost where total cost = Sum of cost of all lines, where the cost of the line is = (Number of extra spaces in the line)2.
Examples:
Input: arr[] = [3, 2, 2, 5], k = 6
Output: 10
Explanation: Given a line can have 6 characters,
Line number 1: From word no. 1 to 1
Line number 2: From word no. 2 to 3
Line number 3: From word no. 4 to 4
So total cost = (6-3)2 + (6-2-2-1)2 = 32+12 = 10. As in the first line word length = 3 thus extra spaces = 6 β 3 = 3 and in the second line there are two words of length 2 and there is already 1 space between the two words thus extra spaces = 6 β 2 -2 -1 = 1. As mentioned in the problem description there will be no extra spaces in the last line. Placing the first and second words in the first line and the third word on the second line would take a cost of 02 + 42 = 16 (zero spaces on the first line and 6-2 = 4 spaces on the second), which isnβt the minimum possible cost.Input: arr[] = [3, 2, 2], k = 4
Output: 5
Explanation: Given a line can have 4 characters,
Line 1: From word no. 1 to 1
Line 2: From word no. 2 to 2
Line 3: From word no. 3 to 3
Same explanation as above total cost = (4 β 3)2 + (4 β 2)2 = 5.
Please Refer Word Wrap Problem for recursive and memoization approaches.
The recursive approach for the word wrapping problem involves trying all possible ways to place words on each line while ensuring that the total length of words (including spaces) does not exceed the line width
k. For each valid configuration, we calculate the cost (squared extra spaces) of the current line and recursively solve the problem for the remaining words. The goal is to minimize the total cost across all lines.We can build itβs recurrence relation as follow:
Let dp[i] represent the minimum cost to wrap words starting from the i-th word until the end. The goal is to calculate dp[0], which will give us the minimumcost to wrap the entire set of words.
For each index i,
- dp[i] = min(cost(i, j) + dp[j+1]) for all j from i+1 to n-1 such that number of characters (including spaces) from i to j does not exceed k.
where,
- cost(i, j) is the cost for wrapping words from index i to j in a single line.
- dp[j+1] is the minimum cost for wrapping words from index j + 1 to the end.
Base Case:
When no words remain, the cost is 0:
dp[n] = 0
10
Time Complexity: O(n^2)
Auxiliary Space: O(n), since n extra space has been taken.