Created
April 12, 2013 12:58
-
-
Save mishadoff/5371821 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 + "]"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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 give1
as final answer. But[2->3,3->2]
is valid and the answer should be2
https://stackoverflow.com/a/15987767/5524175