-1

I am trying to solve a problem:

Given an NxM matrix, each element represents the cost associated to buy an item. Given that we plan to buy M-1 items from each of the N rows, what is the minimum amount that we would have to spend, if we plan to buy items of all M types?
For e.g., if the input is:
2 3 5
3 2 5
4 4 7
the output should be: (2+3) + (2+5) + (4+4) = $20.

I am confused if this is DP or greedy.

I feel it is greedy, since we have to buy M-1 items. So, for each of the three columns in the above example, we could just select the lowest value (2, 2 and 5) and use that towards the calculation of the final result. I considered a few more examples and this logic seems to work, but I do not feel 'confident' about it. I am unable to 'prove' it. Could someone please confirm if I am on the right track?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
P.K.
  • 379
  • 1
  • 4
  • 16

1 Answers1

0

The problem has a greedy solution that is closely related with your idea of selecting the lowest value of each row. Instead of selecting which item you are going to buy, the greedy part is to choose those you are not going to buy (one from each row).

Select the maximum element of each row to throw away. There are two cases:

  1. Every selected element belongs to the same column: search second minimum element of each row and then select the one that minimize: (maximum element of row - second maximum element of row).
  2. There are at least two elements from distinct columns: These elements are the ones you are not going to buy.

2nd case is easy to spot that is true. In the 1st case by problem restrictions there is at least one selected element that do not share the same column that another selected element. Then, you need to choose one of them to be replaced by another element from the same row, if you are going to do that select the one that is nearer to such maximum to decrease the increment of the payment.

That analysis cover all corner cases but obviously it is not formally proved. For that an analysis involving transformation of optimum solution is needed (more o less straightforward when you separate the cases).

Eloy Pérez Torres
  • 1,050
  • 4
  • 14