Last active
June 17, 2021 15:06
-
-
Save GioF71/f4338881ce549eaa04aa747f959c98a9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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