Skip to content

Instantly share code, notes, and snippets.

@nietaki
Created May 13, 2019 11:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nietaki/e3b1182c92dc73712df74ef75fb42483 to your computer and use it in GitHub Desktop.
Save nietaki/e3b1182c92dc73712df74ef75fb42483 to your computer and use it in GitHub Desktop.
public class Solution {
public int solution(int[] radiuses) {
int length = radiuses.length;
int[] startCounts = new int[length];
int[] endCounts = new int[length];
// make sure there's no overflows
for (int i = 0; i < length; i++) {
radiuses[i] = Math.min(length, radiuses[i]);
}
int lastPos = length - 1;
for (int i = 0; i < length; i++) {
int radius = radiuses[i];
int startPos = Math.max(i - radius, 0);
int endPos = Math.min(i + radius, lastPos);
startCounts[startPos]++;
endCounts[endPos]++;
}
// printAll(startCounts);
// printAll(endCounts);
int intersectCount = 0;
int currentLayerCount = 0;
for (int i = 0; i < length; i++) {
int newStarts = startCounts[i];
int newEnds = endCounts[i];
intersectCount += newStarts * currentLayerCount + (newStarts * (newStarts - 1)) / 2;
currentLayerCount = currentLayerCount + newStarts - newEnds;
// short circuit return
if(intersectCount > 10000000) {
return -1;
}
}
return intersectCount;
}
public void printAll(int[] numbers) {
int length = numbers.length;
for (int i = 0; i < length; i++) {
System.out.println(numbers[i]);
}
System.out.println("");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment