Skip to content

Instantly share code, notes, and snippets.

@NodoFox
Last active January 22, 2017 00:39
Show Gist options
  • Save NodoFox/deda1d0299e881a757f646c34eb57510 to your computer and use it in GitHub Desktop.
Save NodoFox/deda1d0299e881a757f646c34eb57510 to your computer and use it in GitHub Desktop.
public int[] rangeAdd(int size, int[][] updates) {
//Concept question since the idea of sorting/merging is more complicated.
// The logic add all values from start index to "end of array" instead of end index.
// But to avoid the additional add, update the end+1 index with negative value(-x).
// This compensates the +x till the end of array. (+x -x = 0)
//res[0,2,3,0,-5]: <- obtained from the first loop.
//sum[0] = res[0] = 0;
//sum[1] = res[0] + res[1] = 0 + 2 = 2;
//sum[2] = res[0] + res[1] + res[2] = 0 + 2 + 3 = 5;
//sum[3] = res[0] + res[1] + res[2] + res[3] = 0 + 2 + 3 + 0 = 5;
//sum[4] = res[0] + res[1] + res[2] + res[3] + res[4] = 0 + 2 + 3 + 0 + (-5) = 0;
//sum[0,2,5,5,0]
int[] result = new int[size];
for(int i = 0; i < updates.length; i++) {
//update result with start values.
int startIndex = updates[i][0];
int value = updates[i][2];
int endIndex = updates[i][1];
result[startIndex] = value;
if(endIndex < size-1) result[endIndex+1] = -value;
}
// adding elemnts from startIndices to end of array instead of end indices
for(int i = 1; i < size; i++) {
result[i] = result[i-1] + result[i];
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment