Find the Value of the Partition - Problem
You are given a positive integer array nums and need to partition it into two non-empty arrays to minimize a specific value.
Goal: Split nums into two arrays nums1 and nums2 such that:
- Each element belongs to exactly one array
- Both arrays are non-empty
- The partition value is minimized
The partition value is defined as: |max(nums1) - min(nums2)|
Example: For nums = [1, 3, 2, 4], if we partition into nums1 = [1, 2] and nums2 = [3, 4], then the partition value is |max([1,2]) - min([3,4])| = |2 - 3| = 1.
Return the minimum possible partition value.
Input & Output
example_1.py โ Basic case
$
Input:
[1, 3, 2, 4]
โบ
Output:
1
๐ก Note:
After sorting: [1, 2, 3, 4]. The optimal partition is [1] and [2, 3, 4] where |max([1]) - min([2,3,4])| = |1 - 2| = 1. All consecutive pairs have difference 1, so minimum is 1.
example_2.py โ Larger gaps
$
Input:
[1, 10, 2, 7]
โบ
Output:
1
๐ก Note:
After sorting: [1, 2, 7, 10]. Consecutive differences are: 2-1=1, 7-2=5, 10-7=3. The minimum difference is 1, achieved by partitioning into [1] and [2, 7, 10].
example_3.py โ Two elements
$
Input:
[5, 8]
โบ
Output:
3
๐ก Note:
With only two elements, there's only one way to partition: [5] and [8]. The partition value is |5 - 8| = 3.
Constraints
- 2 โค nums.length โค 105
- 1 โค nums[i] โค 109
- All elements are positive integers
- Array must be partitioned into exactly two non-empty parts
Visualization
Tap to expand
Understanding the Visualization
1
Line Up Players
Sort all players by their skill levels from weakest to strongest
2
Find Best Split Point
The fairest division occurs where consecutive skill levels are closest
3
Minimize Skill Gap
Choose the split that minimizes the gap between the strongest player on the weaker team and weakest player on the stronger team
Key Takeaway
๐ฏ Key Insight: Sort first, then the minimum partition value is simply the smallest difference between consecutive elements - no complex partition testing needed!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code