Back to Practice Dashboard
Competitive ProgrammingEasy

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

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?
Analyze the input constraints. Try sorting first (O(n log n)) or using a hash map/set to track seen elements in O(n) time.
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.

Open in Editor