Word Wrap

You are given ‘N’ words of various lengths, now you have to arrange these words in such a way that each line contains at most ‘M’ characters and each word is separated by a space character. The cost of each line is equal to the cube of extra space characters required to complete ‘M’ characters in that particular line. Total cost is equal to the sum of costs of each line.

Your task is to form this arrangement with the minimum cost possible and return the minimum total cost.

Note:
The length of each word should be less than or equal to ‘M’.

You can’t break a word, i.e. the entire word should come in the same line and it must not be the case that a part of it comes in the first line and another part on the next line.
Input Format:
The first line of the input contains an integer ‘T’ denoting the number of test cases.

The first line of each Test case should contain two positive integers, ‘N’ and ‘M’, where ‘N’ is the number of words and ‘M’ is the number of characters we require in each line. 

Following ‘N’ lines, contains one word each.
Output Format:
Each test case's only line of output should contain an integer denoting the minimum cost required to form the arrangement. 

Print the output of each test case in a separate line.
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function. 
Constraints:
1 <= T <= 100
1 <= N <= 300
1 <= |words[i]| <= 100
1 <= M <= 100

Time Limit: 1sec
CodingNinjas
author
2y

I first used recursion and then converted it to a dynamic programming based solution.

CodingNinjas
author
2y
Recursion Based Solution
  • Let' suppose we're at the ith word and jth line
  • Suppose we can put 5 words(total characters which are less than m) in the jth line(wi,wi+1......wi+4).
  • Now in this jth line, we wi...read more
CodingNinjas
author
2y
Dynamic Programming Solution
  • Let' suppose we're at the ith word and jth line
  • Suppose we can put 5 words(total characters which are less than m) in jth line(wi,wi+1......wi+4).
  • Now in this jth line, we wi...read more
CodingNinjas
author
2y
bottom Up Dynamic Programming

In This Approach, we will calculate the cost of all possible lines using dynamic programming and then calculate the final cost by taking the minimum from every possible li...read more

Add answer anonymously...
Microsoft Corporation Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter