Firstly notice that there is no difference between space and hyphen, you can replace them with the same character, if you want.
Let's run binary search on answer. Fix width and greedily construct ad — wrap word only if you don't option to continue on the same line. Then check if number of lines doesn't exceed k.
#include <iostream> using namespace std; const int INF = (int)1e9; int n,k,r,l; string s; int solve(int w) { int ans = 0; int l = 0; while(l < n) { ans++; int r = l + w; if (r >= n) break; while(r > l && s[r - 1] != ' ' && s[r - 1] != '-') r--; if (r == l) return INF; l = r; } return ans; } int main() { cin >> k; getline(cin, s); getline(cin, s); n = s.length(); int l = 0, r = n; while(r - l > 1) { int m = (l + r) / 2; if (solve(m) <= k) r = m; else l = m; } cout << r << endl; return 0; }