r/programming • • May 09 '15

"Real programmers can do these problems easily"; author posts invalid solution to #4

https://blog.svpino.com/2015/05/08/solution-to-problem-4
3.1k Upvotes

1.3k comments sorted by

View all comments

1

u/Phildos May 09 '15 edited Nov 12 '25

serious plough march door knee detail degree rob chunky juggle

This post was mass deleted and anonymized with Redact

1

u/chaszzzbrown May 09 '15 edited May 09 '15

Suppose you have a solution S = {s_i}, where each s_i is a string from the given set of numbers; and the 'result' of S is the concatenation s_1 + s_2 + ... s_n. 'S is optimal' means that the result of S is maximal (in the lexical ordering); it is greater than or equal to the result from any other possible sequence.

I will write a >' b to mean (a+b)>(b+a) in the usual lexical order for strings; and write a =' b to mean that a+b = b+a; with >=' and <=' in their obvious extensions.

As a sketch, first I'd show that >' actually is an ordering (i.e., that a >' b and b >' c implies a >' c; and a =' b and b =' c implies a =' c). Then I'd show that if S is optimal, then the elements of S are linearly ordered by >' (this is the key observation); and finally that if any (not necessarily optimal) S and T are linearly ordered by >', then the resulting concatenation is the same.

It follows that since at least one optimal sequence must exist, all linear orders produce the same, optimal result (so we needn't worry about exactly how the sort is accomplished as regards elements a =' b).

I'll prove the second assertion (which is the least persnickety, and really the nugget of the problem). First, given any i, let j = i+1, and let a be the the concatenation of all elements to the left of s_i, and b the same for elements to the right of s_j.

Then the pattern produced by S = a + s_i + s_j + b (a, b possibly empty).

Since S is optimal by assumption, the result produced by swapping the pair = a + s_j + s_i +b certainly cannot be greater than the first result.

This still holds when we discard the prefix and suffix strings a and b from the concatenations, so we can deduce that s_i + s_j >= s_j + s_i (in the lexical order); which is just to say that s_i >=' s_(i+1) for each i.

Thus, if S is optimal, S is linearly ordered by >'. That's what makes >' an ideal candidate for the sorting; although we have to also show the other properties as well.

Whew! That's plenty for a reddit post...

Edit: to get rid of italics, I hope... is LaTeX supported in this sub?