I have an array of Point
s. 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
I have a bit better (than brute force) algorithm.
1: {(x,y): x>y}, 2: {(x,y):x==y}, 3:{(x,y): x lower-than y}
2
have to be always included in the solution.1
define net=x-y
and for each (x,y) form 3
define net=y-x
net
s in 1
and net
s in 3
.Does it make sense?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With