Skip to content

Instantly share code, notes, and snippets.

@TheNerdJedi
Created May 12, 2015 00:27
Show Gist options
  • Save TheNerdJedi/53d2feb1756130e62fc3 to your computer and use it in GitHub Desktop.
Save TheNerdJedi/53d2feb1756130e62fc3 to your computer and use it in GitHub Desktop.
Consec Distance????
package com.interview;
import java.util.Arrays;
public class ConsecutiveDistance {
public static class Element implements Comparable<Element> {
public int magnitude;
public int index;
public Element(int magnitude, int index){
this.magnitude = magnitude;
this.index = index;
}
@Override
public int compareTo(Element o) {
if (magnitude != o.magnitude) {
return magnitude - o.magnitude;
} else {
return index - o.index;
}
}
}
public static int maxDistance(int[] source) {
Element[] elems = new Element[source.length];
for(int i = 0; i < source.length; i++) {
elems[i] = new Element(source[i], i);
}
Arrays.sort(elems);
int maxDistance = 0;
for(int i = 1; i < elems.length; i++) {
if (elems[i].magnitude == elems[i-1].magnitude) {
continue; // Same element doesn't count as consecutive
}
int dist = elems[i].index - elems[i-1].index;
if(dist > maxDistance) {
maxDistance = dist;
}
}
return maxDistance;
}
public static void main(String[] args){
int[] testArr = new int[]{1,3,5,5,12,13,22,2,5};
System.out.println(maxDistance(testArr));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment