text = get_input()line_length = get_input()words = text.split(' ') # Assuming words are split by a single spaceno_of_words = len(words)arr = new array(no_of_words) # arr[i] = cost of justifying words[i:]for each elem in arr: elem = -1justify_text(words, arr) justify_text(words, arr): cur_line = '' # no need to maintain string if u dont want to just maintain # indices for each word in words: if len(word) > line_length - len(cur_line): break # No space left in line!! cur_line += word # Add word by word to each line cur_line += ' ' if arr[indexof(word) + 1] == -1: justify_text(words[1:], arr) # justify the rest of the text new_cost = (line_length - len(cur_line))**3 + arr[indexof(word) + 1] if arr[indexof(word) + 1] == -1 or new_cost < arr[indexof(word)]: arr[indexof(word)] = new_cost # Yaay lower value :-)