Skip to content

Instantly share code, notes, and snippets.

@mishadoff
Created April 12, 2013 12:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mishadoff/5371821 to your computer and use it in GitHub Desktop.
Save mishadoff/5371821 to your computer and use it in GitHub Desktop.
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;
@Override
public String toString() {
return "[" + e + ", " + idx + "]";
}
}
@sumanth-culli
Copy link

sumanth-culli commented Jun 5, 2021

@mishadoff
This won't work for arrays like this [4,100,3,2,1000,1]. Your algo will check for [1->5,2->3,3->2,4->0] and see that this isn't possible and give 1 as final answer. But [2->3,3->2] is valid and the answer should be 2
https://stackoverflow.com/a/15987767/5524175

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment