I have this question on a practise exam, and have no idea how to solve it, so I’m very scared for the final. Anyways, finding that this problem has an answer would be relieving and would help me understand dynamic programming, so thanks for reading 🙂
Problem:
Given a sequence of n numbers a1, …, an (positive or negative), we
want to divide the sequence into blocks so as to minimize the sum of
the squares of the block sums, subject to the constraint that each
block contains at least 2 and at most 4 elements. In other words, we
want to find 1 = i[0] < i[1] < i[2] < … < i[k-1] < i[k] = n + 1 to
minimize (ai[0] + … + ai[1]-1)^2 + (ai[1] + … + ai[2]-1)^2 + … +
(ai[k-1] + … + ai[k]-1)^2, such that 2 <= i[1] – i[0] <= 4, 2 <=
i[2] – i[1] <= 4, …, 2 <= i[k] – i[k-1] <= 4. (Note that the number
of blocks k is not given.) Present an O(n)-time dynamic programming
algorithm to solve the problem.
My problem: defining the subproblems. My only clue is to continuously find the minimum sums of length 4 down to 2, but what if there is 1 leftover? Does it join with an existing group of length 2 or 3, or does a 4-group split? Let alone getting it done in O(n)…
The subproblem is: Find the miminum across the first k numbers.
Here is how you reduce the problem to already solved subproblems:
Let
F(k)be the minimum sum of squares when solved fora1, a2, ... ak.Now
You can write a simple function that computes F(k) for increasing values of k and stores them in an array.