Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting points such that sum of x coordinates = sum of y coordinates

Tags:

java

algorithm

I have an array of Points. I need to select a subset of points from it, such that the sum of x coordinates of the points = sum of y coordinates of the points. If there are many such subsets, the one with largest sum of x coordinates is required. The sum of x coordinates needs to be reported.

I have written a brute force recursive method, which tests all possibilities.

Point[] a = new Point[n];
// ...
private int rec(int i, int x, int y) {
    if (i == n - 1) {
        if (x + a[i].x == y + a[i].y) return x + a[i].x;
        return (x == y) ? x : -1;
    }
    return Math.max(rec(i + 1, x, y), rec(i + 1, x + a[i].x, y + a[i].y));
}

The answer is rec(0, 0, 0).

My questions are:

1) Is there a dynamic programming solution for this?
2) If yes, could anyone please explain

like image 737
xylon97 Avatar asked Nov 30 '13 15:11

xylon97


1 Answers

I have a bit better (than brute force) algorithm.

  1. Divided all coordinates into three sets:
     1: {(x,y): x>y}, 2: {(x,y):x==y}, 3:{(x,y): x lower-than y}
  2. Set 2 have to be always included in the solution.
  3. for each (x,y) from 1 define net=x-y and for each (x,y) form 3 define net=y-x
  4. check all possible values you can obtained from nets in 1 and nets in 3.
  5. then basing on the greatest match it is easy to construct the solution.

Does it make sense?

like image 78
artur grzesiak Avatar answered Oct 08 '22 05:10

artur grzesiak