Skip to content

Instantly share code, notes, and snippets.

@jordanterry
Created October 26, 2014 14:58
Show Gist options
  • Save jordanterry/372273660669caed24ca to your computer and use it in GitHub Desktop.
Save jordanterry/372273660669caed24ca to your computer and use it in GitHub Desktop.
public class TapeEquilibrium {
public int solution(int[] A) {
/*
* Declare some initial variables
* min is the maximum value an Integer could possibly be. (each element of array A is an integer within the range [−1,000..1,000].)
* total will represent the total value of each element in A
* upto will be used to represent the left hand side of the Array
*/
int min = 9999,
total = 0,
upto = 0;
// Count up the total of A by adding each value to the total
for(int a : A) total += a;
// Loop down through each value in A
for(int i = 0; i < A.length - 1; i++) {
// Add a new value to the array
upto += A[i];
/*
* Declare some variables
* left the left hand side is represented by the current value of upto
* the right hand side is the total subtract the value of the left hand side
* the difference between the right hand and left hand side is calculated by subtracting the left from the right
*/
int left = upto,
right = total - left,
diff = Math.abs(right - left);
/*
* The declaration of multiple variables is for readability, the above could be refactored to the following
* int diff = Math.abs(total - (upto * 2));
*/
if(diff < min) {
// If the difference is less than the current minimum, set a new minimum value
min = diff;
} else if(diff == 0) {
// If the difference is 0 return it.
return 0;
}
}
// Return the minimum value
return min;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment