package com.stackoverflow;
import java.util.Arrays;
import java.util.Comparator;
public class ContSubArray {
public static void main(String[] args) {
int[] array =
//{10, 5, 3, 1, 4, 2, 8, 7};
//{10, 5, 24, 3, 1, 4, 2, 8, 7};
//{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1};
{4, 5, 1, 5, 7, 6, 8, 4, 1};
E[] ext = new E[array.length];
for (int i = 0; i < array.length; i++) {
E e = new E();
ext[i] = e;
e.e = array[i];
e.idx = i;
}
System.out.println("Input: " + Arrays.toString(array));
System.out.println("Length: " + find(ext));
}
static int find(E[] array) {
// sort input (can be done in O(n) for integers)
Arrays.sort(array, new Comparator<E>() {
@Override
public int compare(E o1, E o2) {
return o1.e - o2.e;
}
});
System.out.println(Arrays.toString(array));
int maxN = 1;
int sum = 0;
int groupMin = Integer.MAX_VALUE;
int curN = 0;
int prev = -1; // none
for (int i = 0; i < array.length; i++) {
if (curN == 0) {
sum = array[i].idx;
groupMin = array[i].idx;
prev = array[i].e;
curN++;
} else {
if (array[i].e != prev + 1) {
curN = 1;
prev = array[i].e;
sum = array[i].idx;
groupMin = array[i].idx;
} else { // continuous
groupMin = Math.min(groupMin, array[i].idx);
curN++;
sum += array[i].idx;
int estSum = estSum(groupMin, curN);
prev = array[i].e;
if (estSum == sum) {
maxN = Math.max(curN, maxN);
}
}
}
}
return maxN;
}
static int estSum(int a, int n) {
return a * n + (n * (n - 1)) / 2;
}
}
class E {
int e;
int idx;
public String toString() {
return "[" + e + ", " + idx + "]";
}
}