Topics Index

Measure oil with given cans

If you need explanation Read this topic

If you need Answer Take test on this topic

Write a program to measure oil with given cans. Assuming that there is a tank with oil and we have cans in various sizes. Using those cans, we need to measure the required quantity by measuring minimum number of times.

Input (List, int) Output (List)
[1, 2, 4] and 10 [4, 4, 2]
[1, 2, 3] and 20 [3, 3, 3, 3, 3, 3, 2]
[4, 7, 9] and 3 []
[2, 4, 10] and 36 [10, 10, 10, 4, 2]

import java.util.*;
class MeasureOilWithGivenCans
    public static void main(String s[])
        List<Integer> cans = new ArrayList<Integer>();
        int quantity = 10;
        System.out.println("Cans used to measure oil are : " + getCans(cans, quantity));


    public static List<Integer> getCans(List<Integer> inputCans, int quantity) {

Topic: Java ArrayList

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

here we need to measure the oil with the given cans..and here we need to find with min number of times so here we need to measure with highest..
*sort the ArrayList and create the another arraylist to store the res assume name is cans
*and start the for loop and initialize the loop control to list.size()-1 and repeat until it reaches the 0
*check here if i<0 || quantity ==0) than return the cans
* now check if the quantity is greater than the list.get(i) than sub the value from the quantity and add that value to res
if quantity is <= than decrease the i value
* after coming out of the loop check if the quantity is !=0 than return empty list Bcz we can not measure with the given cans
finally return the cans

Note:dont decrease the i value in for loop decrease in the else part

Posted by Uday Kumar    2015-02-12 08:03:51

This dose is now closed and the winners are Uday Kumar,  for 'First Correct Comment'. The 'lucky liker' is Uday Kumar. Please login into Merit Campus using facebook, to claim your recharge. Go to to raise the recharge.

Posted by Merit Campus    2015-02-13 03:56:22

© meritcampus 2019

All Rights Reserved.

Open In App