Competitive ProgrammingEasy

Partition into two subarrays

Detailed guide and Python implementation for the 'Partition into two subarrays' problem.

Problem Statement

Easy

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.

Constraints
  • 1 <= k < len(arr) <= 10^5
  • 1 <= arr[i] <= 10^4

Examples

Example 1
Input
max_difference_subarrays([8, 4, 5, 2, 10], 2)
Output
17
Explanation

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.

Example 2
Input
max_difference_subarrays([1, 1, 1, 1, 1], 3)
Output
1
Explanation

Select 3 elements (sum 3), remaining 2 sum to 2. The difference is 1.

Need a Hint?
Consider using Greedy-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.