COT5405 Analysis of Algorithms Homework 4
The rules for this HW are same as the previous ones. Due date: April 10 Thursday 4 PM (not 5 PM).
1. (Page Limit: 1 page)
Using dynamic programming solve the following problem:
Given
n
integers (
a
1
,...,a
n
) between 0 and
K
, partition them into two subsets such that the
diﬀerence between the sums of each subset is minimized. In other words, if the sum of the ﬁrst
partition is
A
and the sum of the second partition is
B
, we want to have

A

B

to be as small as
possible.
Solution:
Solution using dynamic programming: Let
S
be the sum of all the
n
integers. The problem is
equivalent to minimizing
S/
2

A
, where
A
is the sum of the ﬁrst partition, as we can assume
A
≤
B
.
Let
P
(
i,j
) = 1 if there is a partition of
a
0
,...,a
i
which has sum
j
, and 0 otherwise.
So
P
(
i
) =
max
{
P
(
i

1
,j
)
,P
(
i

1
,j

A
i
))
}
. The ﬁrst part comes from the fact that if you have
a partition of
a
0
,...,a
i
with sum
j
, you also have a partition of
a
0
,...,a
i
+1
with sum
j
. The second
part is obvious.
To solve the problem using this recurrence, just work up till
P
(
S/
2) and ﬁnd the largest
m
such
that
P
(
m
) = 1. The diﬀerence between the partitions would be 2
m
. Of course one also needs to
use the
P
(
i
) table until the partitions are recovered  which is straightforward.
The worst case running time would be
O
(
n
2
K
)
Grading criteria:
If you gave a heuristicbased algorithm, you will be penalized heavily since such algorithms always
fail to give the correct result for some deliberately crafted input set, i.e., such algorithms are not
deterministic about their accuracy.
If you have an algo that is exponential, you would be penalized heavily.
Many of you contended that the problem is NPcomplete and thus unsolvable in polynomial time.
That would be true, if we did not know about the size of the individual integers. In this speciﬁc
problem, we gave that each integer is bounded by
K
. That makes the algorithm
O
(
n
2
K
), or
polynomial.
Those who did not give any complexity analysis lost 5 points (and gained a “C ?” annotation). If
you did the complexity analysis as
O
(
nS
) where you stated
S
is the sum of the
n
numbers, you
would still lose couple of points since
S
=
O
(
nK
), and thus the complexity =
O
(
nS
) =
O
(
n
2
K
).
I understand this is more of a formality, but the truth is that we had provided all the necessary
parameters with which you can express the complexity as. If we did not supply
K
, then you had
a point of using
S
, as without using that it would have been impossible to express the complexity.
Besides, the penalty is not that harsh.
2. (Page Limit: 1 page)
1