You are given an array W, W, …, W[N]. Choose K numbers among them such that the absolute difference between the sum of chosen numbers and the sum of remaining numbers is as large as possible.
Input : arr = [8, 4, 5, 2, 10] k = 2 Output: 17 Input : arr = [1, 1, 1, 1, 1, 1, 1, 1] k = 3 Output: 2
There are two possibilities to get the desired answer. These two are:Choose k largest numbers or Choose k smallest numbers. Choose the best-suited option which fits according to the given values. This is because there are some cases in which the sum of smallest k numbers can be greater than rest of the array and there are some cases in which the sum of largest k numbers can be greater than rest of the sum of the numbers.
- Sort the given array.
- Get the sum of all the numbers of the array and store it in sum
- Get the sum of first k numbers of the array and store it in sum1
- Get the sum of last k numbers of the array and store it in sum2
- Output the result which is : max(abs(S1-(S-S1)), abs(S2-(S-S2)))
This article is contributed by Rishabh Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- k size subsets with maximum difference d between max and min
- Maximum absolute difference in an array
- Maximum sum of absolute difference of an array
- Maximum difference between groups of size two
- Minimize the maximum difference between the heights
- Maximum possible difference of two subsets of an array
- Maximum sum of pairs with specific difference
- Largest subset with maximum difference as 1
- Maximum difference between two subsets of m elements
- Maximum difference of indices (i, j) such that A[i][j] = 0 in the given matrix
- Maximum difference between first and last indexes of an element in array
- Minimize the difference between minimum and maximum elements
- Find the sum of maximum difference possible from all subset of a given array.
- Maximum absolute difference between sum of two contiguous sub-arrays
- Maximum absolute difference of value and index sums