1
0
Fork 0
mirror of https://gitlab.com/mfocko/CodeWars.git synced 2024-09-16 20:56:57 +02:00
CodeWars/6kyu/consecutive_strings/solution.java
Matej Focko fc899b0b02
chore: initial commit
Signed-off-by: Matej Focko <mfocko@redhat.com>
2021-12-28 16:19:58 +01:00

42 lines
1 KiB
Java

class LongestConsec {
public static String longestConsec(String[] strarr, int k) {
int n = strarr.length;
// handle limits
if (n == 0 || k <= 0 || k > n) {
return "";
}
// determine lengths
int[] lengths = new int[n];
for (int i = 0; i < n; i++) {
lengths[i] = strarr[i].length();
}
// calculate first index
int maxIndex = 0, maxLength = 0;
for (int i = 0; i < k; i++) {
maxLength += lengths[i];
}
// Check rest of the array
int tmpLength = maxLength;
for (int i = 1; i < n - k + 1; i++) {
tmpLength += lengths[i + k - 1];
tmpLength -= lengths[i - 1];
if (tmpLength > maxLength) {
maxIndex = i;
maxLength = tmpLength;
}
}
// Join the strings
String result = "";
for (int i = maxIndex; i < maxIndex + k; i++) {
result += strarr[i];
}
return result;
}
}