1
0
Fork 0
mirror of https://gitlab.com/mfocko/CodeWars.git synced 2024-11-09 19:19:07 +01:00
CodeWars/6kyu/consecutive_strings/solution.java

43 lines
1 KiB
Java
Raw Normal View History

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;
}
}