Given an array of integers, what is the maximum sum of a subset of the integers such that the integers in the subset were not originally next to each other?
Examples:
[3, 8, 4] => max sum is 8, since 8 > (3+4)
[12, 8, 9, 10] => max sum is 12 + 10 = 22, since this is greater than 12 + 9 and 8 + 10
I’m interested in figuring out the algorithm for doing this. Methodology / thinking process = greatly appreciated.
EDIT:
The integers range from 1 to 1000, inclusive. (Since this is entirely a learning exercise, I’d still be interested in learning about different methods if the integers ranged from, say, -1000 to 1000.)
Let you have array
A {Ai, 1 <= i <= n }F(i)– Maximum sum of subarrayAj { 1 <= j <= i }, thenF(0) = 0– empty subarrayF(1) = A(1)– only first elementF(n)– answerC++ implementation:
Explanation:
First, main idea is to use dynamic programming.
We try to solve task for array with N element by using known answer for array with
N-1andN-2first elements. IfN = 0the answer is0and ifN = 1the answer isA[1]. It’s clear. ForN >= 2we have 2 different ways:Use element
A[N],then the answer isA[N] + F[N-2](because we can’t use A[N-1] element andF[N-2]is the best solution for subarray1..N-2, we don’t care about ifF[N-2]element is used or not, this is just the best solution for subarray1..N-2.Don’t use element
A[N], then the answer isF[N-1](because we can use A[N-1] element andF[N-1]is the best solution for subarray1..N-1, also we don’t care about ifF[N-1]element is used or not.So we need to get max of this 2 situations.
To solve the task you need calculate
F[N]in increasing order and memorize answers.Let see at your example:
[12, 8, 9, 10]F[0] = 0F[1] = 12– use 1-st elementF[2] = max(F[0]+A[2], F[1]) = max(8, 12) = 12– use 1-st elementF[3] = max(F[1]+A[3], F[2]) = max(21, 12) = 21– use 1-st, 3-rd elementF[4] = max(F[2]+A[4], F[3]) = max(22, 21) = 22– use 1-st, 4-th elementThe answer is
F[4] = 22.