My main question is how to optimize this so that it really returns a solution other than that it passed the -O flag to ghc, which I already did.
I think you should reconsider your approach. I think this problem is not so much in coding skills as in solving problems. Trying all possible permutations is brute force, and I think that now you have a good feeling why this brute force strategy does not work in this case;). This can actually be done in 3 lines of code when you use stl algorithms (not counting input and output, of course).
In fact, Madan Ram has already given some kind of solution. However, if you are ever given such a problem in an interview, you will also need to know why it works in all cases (not just for a number of examples). Therefore, my advice is to take a pen and a piece of paper and make some examples by hand, then you will learn how to do it.
SPOILER WARNING
It's hard to give a hint without spoiling a lot, but since the solution has already been published ... Try to start simply. Which element in the first vector has the greatest contribution to the scalar product? To which element of the second vector do you need to do this in order to get the least contribution to the scalar product?
source share