(UVA) Boiled Eggs - Solution

Link to the problem: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=658&page=show_problem&problem=3051

The solution below used a Greedy approach to solve this problem.

The array of eggs is in ascending order (the eggs that are softer come first). Then, in order to use the maximum number of eggs, we only need to start considering using an egg from the beginning of the array.


import java.io.*;
import java.util.*;

class Main {
    public void process() throws NumberFormatException, IOException {
        Scanner sc = new Scanner(System.in);
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        int numTests = sc.nextInt();
        for (int test = 0; test < numTests; test++) {
            int numEggs = sc.nextInt();
            int numMaxEggs = sc.nextInt();
            int maxWeight = sc.nextInt();
           
            int numUsedEggs = 0;
            int sumWeight = 0;
            for (int i = 0; i < numEggs; i++) {
                int currEggWeight = sc.nextInt();
                if (numUsedEggs+1 <= numMaxEggs && sumWeight+currEggWeight <= maxWeight) {
                    sumWeight += currEggWeight;
                    numUsedEggs++;
                }
            }       
           
            bw.write("Case " + (test+1) + ": " + numUsedEggs + "\n");           
        }
                                              
        bw.flush();
        bw.close();
       
        return;
    }
   
    public static void main(String[] args) throws NumberFormatException, IOException {
        Main m = new Main();
        m.process();
       
        System.exit(0);
    }
}

Comments

Popular posts from this blog

(Coderbyte) Dash Insert II - Solução

(Coderbyte) Run Length - Solução

(Coderbyte) Counting Minutes I - Solução