-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay9Part2.java
59 lines (48 loc) · 1.79 KB
/
Day9Part2.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package uk.oczadly.karl.aoc20.solution.day9;
import uk.oczadly.karl.aoc20.input.PuzzleInput;
import uk.oczadly.karl.aoc20.input.NoValidSolutionException;
import uk.oczadly.karl.aoc20.PuzzleSolution;
import java.util.List;
/**
* @author Karl Oczadly
*/
public class Day9Part2 extends PuzzleSolution {
public Day9Part2() { super(9, 2); } // Initializes the day and part number
@Override
public Object solve(PuzzleInput input) {
List<Long> in = input.asList(Long::parseLong);
// Find invalid number
long targetNum = 0;
for (int i = 25; i < in.size(); i++) {
long num = in.get(i);
boolean isValid = false;
validCheck: for (int j = i - 25; j < i; j++) {
for (int k = i - 25; k < i; k++) {
if (j != k && in.get(j) + in.get(k) == num) {
isValid = true;
break validCheck;
}
}
}
if (!isValid) {
targetNum = num;
break;
}
}
// Find set of numbers that add up to 'targetNum'
for (int startIndex = 0; startIndex < in.size(); startIndex++) {
long currentSum = 0, min = Long.MAX_VALUE, max = Long.MIN_VALUE;
for (int i = startIndex; i < in.size(); i++) {
long val = in.get(i);
currentSum += val;
if (val < min) min = val;
if (val > max) max = val;
if (i > startIndex && currentSum == targetNum) {
// Solution found!
return min + max;
}
}
}
throw new NoValidSolutionException();
}
}