Suppose you get an array of ints of arbitrary length. Now we need to find out what is the mimimal absolute difference of the 2 sums of numbers if you split the array at any position in a left and right array. And preferably in a efficient way.
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
import java.util.ArrayList; | |
import java.util.List; | |
public class TapeEquilibrium { | |
public static void main(String[] args) { | |
int [] numbers1 = {1,3,2,7}; | |
int [] numbers2 = {5,2,8,4}; | |
evaluate(numbers1, 1); | |
evaluate(numbers2, 5); | |
} | |
public static void evaluate(int [] numbers, int expected) { | |
int answer = solution(numbers); | |
System.out.println("Expected answer = " + expected + ", got " + answer); | |
} | |
public static int solution(int[] A) { | |
List<Integer> numbers = toList(A); | |
int size = numbers.size(); | |
int sumLeft = numbers.get(0); | |
int sumRight = sum(numbers.subList(1, size)); | |
int minDifference = Math.abs(sumLeft - sumRight); | |
for (int i : numbers.subList(1, size -1)) { | |
sumLeft = sumLeft + i; | |
sumRight = sumRight - i; | |
int difference = Math.abs(sumLeft - sumRight); | |
if (difference < minDifference) { | |
minDifference = difference; | |
} | |
} | |
return minDifference; | |
} | |
public static List<Integer> toList(int [] array) { | |
List<Integer> result = new ArrayList<Integer>(); | |
for (int ele : array) { | |
result.add(new Integer(ele)); | |
} | |
return result; | |
} | |
public static int sum(List<Integer> numbers) { | |
int sumRight = 0; | |
for (int i : numbers) { | |
sumRight += i; | |
} | |
return sumRight; | |
} | |
} |
It has reminded me of the in-place version of quicksort algorithm: http://en.wikipedia.org/wiki/Quicksort#In-place_version
ReplyDeleteBTW, a couple of improvements to your implementation:
1. You should avoid using Arrays.copyOfRange. It's so inefficient.
2. You can immediately break the loop as soon as the following becomes true: (difference > minDifference).
Well, my second point is incorrect if there may be negative ints.
ReplyDeleteYeah.... arrays are a pain to work with... I probably should convert the int array to a List first but even that takes a few lines of code extra... java does not autobox them unfortunately. But with a list I can easily take subLists.
ReplyDeleteHi, Thanks for this great image that explores and helps me to understand what the Tape-Equilibrium is!.
ReplyDelete