1

The question Maximum single-sell profit returns one pair. How can you build upon any of the sub O(n^2) algorithm to find all pairs sorted by profit?

Ex.

values: scala.collection.immutable.Vector[Int] = Vector(1, 5, 10, -5, 0, -10, 15)
pairsAsc: Vector[(Int, Int)] = Vector((5,6), (3,6), (0,6), (0,2), (3,4))
gains: scala.collection.immutable.Vector[Int] = Vector(25, 20, 14, 9, 5)
Community
  • 1
  • 1
ferk86
  • 2,325
  • 1
  • 23
  • 27

1 Answers1

2

It's Sorting-X+Y-hard, so it's unreasonable to expect an o(n^2 log n)-time algorithm (in some reasonable model of computation).

The reduction is, given arrays x1, … xn > 0 and y1, … yn > 0, let Z > max(x1, … xn, y1, … yn). Let the input to this problem be Z - x1, …, Z - xn, 3Z + y1, …, 3Z + yn. All of the X-X differences and Y-Y differences are less than Z. All of the X-Y differences are greater than Z. This makes it easy to filter the output, solving the original problem.

David Eisenstat
  • 64,237
  • 7
  • 60
  • 120