
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Minimum Costs to Fill Fruits in Optimized Way in Python
Suppose we have a list called fruits and another two values k and cap. Where each fruits[i] has three values: [c, s, t], this indicates fruit i costs c each, size of each of them is s, and there is total t of them. The k represents number of fruit baskets of capacity cap. We want to fill the fruit baskets with the following constraints in this order −
- Each basket can only hold same type fruits
- Each basket should be as full as possible
- Each basket should be as cheap as possible
So we have to find the minimum cost required to fill as many baskets as possible.
So, if the input is like fruits = [[5, 2, 3],[6, 3, 2],[2, 3, 2]] k = 2 cap = 4, then the output will be 12, because we can take two fruit 0s because with these two, we can make the first basket full for total size 2+2=4, it costs 5+5=10. Then, we use one of fruit 2 because it is cheaper. This costs 2 unit.
To solve this, we will follow these steps −
- options := a new list
- for each triplet (c, s, t) in fruits, do
- while t > 0, do
- fnum := minimum of floor of (cap / s) and t
- if fnum is same as 0, then
- come out from loop
- bnum := floor of t / fnum
- insert triplet (cap - fnum * s, fnum * c, bnum) at the end of options
- t := t - bnum * fnum
- while t > 0, do
- ans := 0
- for each triplet (left_cap, bcost, bnum) in the sorted list of options, do
- bfill := minimum of k and bnum
- ans := ans + bcost * bfill
- k := k - bfill
- if k is same as 0, then
- come out from loop
- return ans
Example
Let us see the following implementation to get better understanding −
def solve(fruits, k, cap): options = [] for c, s, t in fruits: while t > 0: fnum = min(cap // s, t) if fnum == 0: break bnum = t // fnum options.append((cap - fnum * s, fnum * c, bnum)) t -= bnum * fnum ans = 0 for left_cap, bcost, bnum in sorted(options): bfill = min(k, bnum) ans += bcost * bfill k -= bfill if k == 0: break return ans fruits = [[5, 2, 3],[6, 3, 2],[2, 3, 2]] k = 2 cap = 4 print(solve(fruits, k, cap))
Input
[[5, 2, 3],[6, 3, 2],[2, 3, 2]], 2, 4
Output
12