Partition into two subarrays
Learn how to solve the 'Partition into two subarrays' problem. This detailed resource details brute force and optimized approaches.
Problem Statement
Write a function max_difference_subarrays(arr, k) that takes an array arr of size n and an integer k. It selects a subset of k elements from arr such that the absolute difference between the sum of the selected elements and the sum of the remaining n-k elements is maximized, and returns this maximum absolute difference.
- •1 <= k < len(arr) <= 10^5
- •1 <= arr[i] <= 10^4
Examples
max_difference_subarrays([8, 4, 5, 2, 10], 2)
17
If we select the 2 smallest elements {2, 4} (sum 6), the remaining elements are {8, 5, 10} (sum 23). The difference is |23 - 6| = 17.
max_difference_subarrays([1, 1, 1, 1, 1], 3)
1
Select 3 elements (sum 3), remaining 2 sum to 2. The difference is 1.
Need a Hint?
Edge Cases to Watch
- Empty list or null input variables
- Single item lists/arrays
- Extremely large input bounds causing integer or stack overflow
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.