text = get_input() line_length = get_input() words = text.split(' ') # Assuming words are split by a single space no_of_words = len(words) arr = new array(no_of_words) # arr[i] = cost of justifying words[i:] for each elem in arr: elem = INT_MAX justify_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 += ' ' justify_text(words[1:], arr) # justify the rest of the text new_cost = (line_length - len(cur_line))**3 + arr[indexof(word) + 1] if new_cost < arr[indexof(word)]: arr[indexof(word)] = new_cost # Yaay lower value :-)