Algorithm to find best option

Viewed 42

I have multiple key:value and need to find the best possible option.

Product Price Product Price Product Price
label1 11 label2 12 label3 13
label4 14 label5 15 label6 16

I need to find all possible options starting from the first column and find best solution like an example:

Product Price Product Price Product Price SUM Result
label1 11 label2 12 label3 13 36
label1 11 label2 12 label6 16 39
label1 11 label5 15 label3 13 39
label1 11 label5 15 label6 16 42
label4 14 label5 15 label6 16 45 label4-label5-label6
label4 14 label5 15 label3 13 42
label4 14 label2 12 label3 13 39
label4 14 label2 12 label6 16 42

Please, any language, I need to understand algorithm

1 Answers

It seems like you are trying to maximize the sum and there is no constraint other than having only one item from each column. In that case: just take the item with the maximum value from each column.

Pseudo code:

res = []
for each col in cols:
  item = getMaxItem(col)
  res.push(item)

getMaxItem(col):
  item = col[0]
  for each i in col:
    if i.price > item.price:
      item = i
  return item

This would be an O(n) solution, with n being the number of items in all the columns.

Related