Please refer https://en.wikipedia.org/wiki/Line_wrap_and_word_wrap#Minimum_raggedness.
Given a list of strings, wrap them in a way to minimize the sum of squared space left over in each line.
Please refer https://en.wikipedia.org/wiki/Line_wrap_and_word_wrap#Minimum_raggedness.
Given a list of strings, wrap them in a way to minimize the sum of squared space left over in each line.
@bigoffer4all Classical dynamic programming problem
def textJustification(words,m):
bad = [[i - j + sum(len(s) for s in words[j:i + 1]) for j in range(len(words))] for i in range(len(words))]
dp = list(range(len(words) + 1))
for i in range(1, len(dp)):
res = float('inf')
for j in range(1, i + 1):
diff = m - bad[i - 1][j - 1];
if (diff >= 0):
res = min(diff * diff + dp[j - 1], res)
dp[i] = res
return dp[len(words)]
@agave I will make a try to explain the algorithm