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