HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Dynamic Program to solve an NP-complete partitioning problem

Submitted by: @import:stackexchange-cs··
0
Viewed 0 times
problemprogramcompletesolvedynamicpartitioning

Problem

I have this problem for which I am struggling to find an efficient dynamic programming algorithm. Would be thankful for some help!!

Let $A = \{ a_1, a_2, ..., a_n \}$ be a set where $a_i \in \mathbb{N}$ for $i=1,...,n$.

The goal is to determine whether there exist two disjoint subsets $M,N \subset A$ such that the sum of all elements in $M$ is equal to exactly $\textit{twice}$ the sum of all elements in $N,$ and $M \not = \emptyset$ and $N \not = \emptyset.$

Solution

Let $\sigma(S)$ denote the sum of all the elements in $S$ and $A_i = \{a_1, \dots, a_i\}$.

Given, $i=0,\dots,n$ and $w \in \mathbb{Z}$,
define $OPT[i,w]$ as the mazimum cardinality of a subset $S \cup S' \subseteq A_i$ where $S \cap S' = \emptyset$
and $\sigma(S) - 2\sigma(S') = w$.
If no possible choice for $S$ and $S'$ exists, then let $OPT[i,w]=-\infty$.

According to the above definition:
$$
OPT[0, w] =
\begin{cases}
0 & \text{if } w=0 \\
-\infty & \text{if } w \neq 0 \\
\end{cases}
$$

For $i>0$:
$$
OPT[i, w] = \max\{ OPT[i-1, w], 1 + OPT[i-1, w-a_i], 1+ OPT[i-1, w+2a_i] \}.
$$

The answer to your problem is true iff $OPT[n, 0] > 0$.
Each $OPT[i, w]$ can be computed in constant time (if you have already computed the values of $OPT[i-1, \cdot]$).
Moreover, there are only $O(n)$ possible choices for $i$ and $O(t)$ sensible choices for $w$, where $t = \sum_{i=1}^n a_i$.
This gives you a dynamic programming algorithm with time complexity $O(n t)$ and space complexity $O(t)$.

Context

StackExchange Computer Science Q#123830, answer score: 2

Revisions (0)

No revisions yet.