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 firstname.lastname@example.org. 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.
- Maximum sum such that no two elements are adjacent
- Maximum and minimum of an array using minimum number of comparisons
- Maximum difference between two elements such that larger element appears after the smaller number
- Sliding Window Maximum (Maximum of all subarrays of size k)
- Given an array arr, find the maximum j - i such that arr[j] > arr[i]
- Maximum Length Bitonic Subarray | Set 1 (O(n) time and O(n) space)
- Find the maximum element in an array which is first increasing and then decreasing
- Maximum Sum Increasing Subsequence | DP-14
- Maximum Product Subarray
- Maximum circular subarray sum
- Find the row with maximum number of 1s
- Maximum sum rectangle in a 2D matrix | DP-27
- Maximum Subarray Sum using Divide and Conquer algorithm
- Find the maximum repeating number in O(n) time and O(1) extra space
- Find the Increasing subsequence of length three with maximum product