Programmer interview question 15: array Segmentation

Source: Internet
Author: User

I. Question Overview: There is a positive integer array with no sorting and the number of elements is 2n. It is required to divide it into two arrays whose number of elements is N, and make the sum of the two subarrays closer to the nearest.
Assume that the sum of all elements in array a [1 .. 2n] is sum. Simulate the dynamic programming strategy to solve the 0-1 knapsack problem, so s (K, I) represents the sum of any I elements in the first k elements. Apparently:
S (k, 1) = {A [I] | 1 <= I <= k}
S (K, K) = {A [1] + A [2] +... + A [k]}
S (K, I) = S (K-1, I) U {A [k] + x | X belongs to S (K-1, I-1 )}
Calculate according to this recursive formula, and finally find the sum closest to the sum in the Set S (2n, n). This is the answer. The time complexity of this algorithm is O (2 ^ N ).
In this process, we only care about the sum of the subarrays not greater than sum/2. Therefore, duplicate sums in the set and sums greater than sum/2 are meaningless. Remove the meaningless sum, and the number of meaningful sums is sum/2 at most. Therefore, we do not need to record the sums in S (2n, n). We only need to traverse sum/2 to 1 and query whether the values are in S (2n, n) one by one) the first value is the answer. Our program does not need to calculate each set according to the above recursive formula. We only need to set a flag array for each set, marking which values in the range of sum/2 to 1 can be calculated. The key code is as follows:

# Include <iostream> using namespace STD; // There is a positive integer array without sorting and the number of elements is 2n. It is required to divide it into two arrays whose number of elements is N, and make the sum of the two subarrays closer to the nearest. Int arr [] = {0, 1, 5, 7, 8, 9, 6, 3, 11, 20, 17}; const int n = 5; const int sum = 87; // simulates the dynamic programming policy int solve1 () {int I, j, S; int DP [2 * n + 1] [n + 1] [sum/2 + 2];/* use dp (I, j, c) to represent the best (large) solution where J elements are obtained from the first I element and the sum of these J elements cannot exceed C. Here I> = J, c <= s state transition equation: limited to I items do not take dp (I, j, c) = max {dp (I-1, J-1, C-A [I]) + A [I], dp (I-1, J, c)} dp (2n, N, sum/2 + 1) is the solution of the problem. * // Initialize memset (DP, 0, sizeof (DP); for (I = 1; I <= 2 * n; ++ I) {for (j = 1; j <= min (I, n); ++ J) {for (S = sum/2 + 1; S> = arr [I]; -- S) {DP [I] [J] [s] = max (DP [I-1] [J-1] [S-Arr [I] + arr [I], DP [I-1] [J] [s]);} // because this is the final answer DP [2 * n] [N] [sum/2 + 1]; I = 2 * n, j = N, S = sum/2 + 1; while (I> 0) {If (DP [I] [J] [s] = DP [I-1] [J-1] [S-Arr [I] + arr [I]) // determine which State is derived from {cout <arr [I] <""; // arr [I] J --; s-= arr [I];} I --;} cout <Endl; return DP [2 * n] [N] [sum/2 + 1];} int solve2 () {int I, j, s; int DP [n + 1] [sum/2 + 2]; // obtain n + 1 items, total sum/2 + 2: The maximum value of memset (DP, 0, sizeof (DP); // The initial status is 0for (I = 1; I <= 2 * n; ++ I) {for (j = 1; j <= min (I, n); ++ J) {for (S = sum/2 + 1; S> = arr [I]; -- S) // 01 the size of the backpack ranges from large to small, saving space, that is, the space of the outermost layer {DP [J] [s] = max (DP [J-1] [S-Arr [I] + arr [I], DP [J] [s]) ;}}// the space cannot be optimized if the optimal solution is required. Return DP [N] [sum/2 + 1] ;}int solve3 () {int I, j, s; int isok [n + 1] [sum/2 + 2]; // isok [I] [v] indicates whether I count can be found, so that the sum of them is equal to vmemset (isok, 0, sizeof (isok); // they are not legal // note that the initialization of isok [0] [0] = 1; // yes, take 0 items. The total value is 0. It is legal for (I = 1; I <= 2 * n; ++ I) {for (j = 1; j <= min (I, n); ++ J) {for (S = sum/2 + 1; S> = arr [I]; -- S) // from large to small, the array is missing a one-dimensional {If (isok [J-1] [S-Arr [I]) isok [J] [s] = 1 ;}}} for (S = sum/2 + 1; S> = 0; -- S) {If (isok [N] [s]) return s ;} // return 0 cannot be optimized if the optimal solution is required.} int main (void) {int S1 = solve1 (); int S2 = solve2 (); int S3 = solve3 (); cout <"S1 =" <S1 <Endl; cout <"S2 =" <S2 <Endl; cout <"S3 =" <S3 <Endl; System ("pause"); Return 0 ;}

Ii. Expansion problem: swap two array elements to minimize the difference between two arrays and
There are two arrays A and B with N sizes. The values of the array elements are unordered due to any integer value;
Requirement: by exchanging elements in arrays A and B, the difference between the sum of Elements A and B is minimized.
In fact, this problem is the deformation of the above problem. The arrays A and B are merged into an array, then the problem is converted to dividing the arrays of 2 * n elements into two arrays with the length of N and bringing the sum of the two arrays closer to the nearest.
Note:If there is a negative number in the array, the above backpack policy cannot be used (because the S in the third loop is used as the lower mark of the array, there cannot be a negative number ), add the absolute value of the smallest negative number to all arrays in the array, and add all elements in the array to a certain range. All elements are converted to positive numbers, then we can solve the problem by using the above backpack policy.

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.