DEV Community

Priyanshu srivastava
Priyanshu srivastava

Posted on

Advent of Code: Day 1

For this puzzle we can make use of a max-heap to store the sum of calories carried by the elves in a descending order.

for part 1 of the problem we can peek the max-heap for the maximum calories

and for part 2 we can loop over the max-heap and find the sum of max-3 calories carried.

We can make use of a PriorityQueue in reverse order to make a max-head in java

import java.io.File;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Scanner;

public class Day1 {
    public static void main(String[] args) throws Exception {
        String path = "D:\\projects\\AdventOfCode\\src\\input.txt";
        File input = new File(path);
        Scanner sc = new Scanner(input);
        var pq = new PriorityQueue<Integer>(Collections.reverseOrder()); // max-heap
        int calories = 0;

        while (sc.hasNextLine()) {
            String calorie = sc.nextLine();
            // reset for new elf
            if (calorie.equals("")) {
                pq.offer(calories);
                calories = 0;
                continue;
            }

            calories += Integer.parseInt(calorie);
        }

        System.out.println("Result part 1 : " + pq.peek());

        int res = 0;
        for (int i = 0; i < 3; i++) {
            res += pq.poll();
        }

        System.out.println("Result part 2 : " + res);
        sc.close();
    }
}
Enter fullscreen mode Exit fullscreen mode

Oldest comments (0)