Each time you fill a bucket of 10 liters, you will have 10 fewer liters in your source bucket.
Each time you fill a bucket of 2 liters, you will have 2 fewer liters in your source bucket.
Each time you fill a bucket of 50 liters, you will have 50 fewer liters in your source bucket.
Can we generalize this?
Each time you fill a bucket of N liters, you will have N fewer liters in your source bucket.
You can’t have fewer than zero liters in your source bucket, so what you’ll actually fill is the lesser of what’s in the source bucket and what the capacity of the destination bucket is.
Since that’s the amount you filled,
Each time you fill a bucket of N liters, you will have min(N, source_bucket_capacity) fewer liters in your source bucket.
While you have water in the source bucket, keep filling buckets. Stop when the source bucket is empty or you have no more destination buckets.
So
- set up the source bucket.
- set up a list of destination buckets.
- while the source bucket is not empty and you have unfilled buckets in the destination list
- get the next destination bucket.
- fill it to min(N, source_bucket_capacity)
- decrement the source bucket by min(N, source_bucket_capacity)
solved Need an algorithm to solve this problem [closed]