-3

we have few items sorted in a particular order... all items have associated prices p(p1, p2...pn) say

item1 - p1

item2 - p2

. . .

itemn - pn

we have x amount to buy items. and initially 0 < x <= p

after each iteration x will become x-p1, x-(p1+p2)....x-(p1+p2+...pn)....at any point if we find that any itemK with price pk > current value of x we will remove that item from the list and buy the next item

we will again run this till either x=0 (amount gets exhausted) or list is empty (all items are of value > current value of x and are removed from the list)

function will return no. of purchases per items

right now i can think of a python dict/list based approach to do this, where we will loop through the above scenario, do a .remove(item) where ever applicable.

but its too much iteration hungry. wondering if theres a better mathematical approach to find this efficiently.

Curi0usM3
  • 33
  • 5
  • This is the [subset sum problem](https://en.wikipedia.org/wiki/Subset_sum_problem) which has an "exponential" complexity. – trincot May 07 '17 at 13:17

1 Answers1

1

This is the best you can do. (The way you mentioned). And it needs just one pass. There is no as such mathematical approach.

For your method - O(n) 1 pass.

Check your question...it is kind of simulation question. Is this what you want? *. You never mentioned if you want to maximize the purchased item.

But if you want to maximize the number of items then it's a different level of question.. Then you would have to read 0-1 knapscak prblem.

user2736738
  • 30,591
  • 5
  • 42
  • 56