Skip to content

Instantly share code, notes, and snippets.

@GioF71
Last active June 17, 2021 15:06
Show Gist options
  • Save GioF71/f4338881ce549eaa04aa747f959c98a9 to your computer and use it in GitHub Desktop.
Save GioF71/f4338881ce549eaa04aa747f959c98a9 to your computer and use it in GitHub Desktop.
private static long nonNaive(List<Long> values, long sum) {
Long result = null;
List<Long> sorted = values.stream().filter(x -> x <= (SUM - 2)).collect(Collectors.toList());
sorted.sort(Comparator.naturalOrder());
for (int i = 0; result == null && i < sorted.size() - 2; ++i) {
long a = sorted.get(i);
boolean offRange = false;
for (int j = i; !offRange && result == null && j < sorted.size() - 1; ++j) {
long b = sorted.get(j);
long partial = a + b;
offRange = partial >= (SUM - b);
if (!offRange) {
// search third addendum
long toBeFound = SUM - partial;
int k = j + i + Collections.binarySearch(sorted.subList(j + 1, sorted.size()), toBeFound);
if (k > j) {
// found match that sums to 2020
// now calculating the result
result = a * b * toBeFound;
}
}
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment