Algorithm--An array of cuts

Source: Internet
Author: User

Title Source: The beauty of programming 2.18

There is an unordered array of positive integers with a number of elements of 2n, which requires:

How can I cut this array into two arrays with an element number n , making the two sub-arrays as close as possible to each other.


Parse: Because the sum of two sub-arrays is certain, equal to the sum of the entire array. Today, the requirement to make two word groups and as close as possible, it means to choose from the n number so that the N number and as close to SUM/2 as possible, it is best to set the direction from a small sum/2 approach. So. This is the question of a 01 knapsack:

Now there are 2N items, each item weighs a[i], there is a backpack size of SUM/2, now from which to pick out n items, so that the backpack as far as possible to be filled.

The recursive formula is then defined as:

DP[I][J][V] = max (Dp[i-1][j][v], dp[i-1][j-1][v-a[i]]+a[i]);

DP[I][J][V]: Select J from the previous I items, weight not greater than the maximum of V and.


The print section above is a sub-array in the printing. Returns the minimum difference of the last two arrays.

Time complexity: O (N*n*sum)


Expansion: Assume that the above code is only required to calculate the last difference, without the need to print out the result array. Then we can reduce the complexity of time to n*sum.

The code is:


Finally the result is that the value of the largest V of the f[n][v]==true is the one you are seeking. (V is reduced from SUM/2).



Copyright notice: This article Bo Master original article. Blog, not reproduced without consent.

Algorithm--An array of cuts

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.