Find the Value of the Partition - Problem

You are given a positive integer array nums.

Partition nums into two arrays, nums1 and nums2, such that:

  • Each element of the array nums belongs to either the array nums1 or the array nums2.
  • Both arrays are non-empty.
  • The value of the partition is minimized.

The value of the partition is |max(nums1) - min(nums2)|.

Here, max(nums1) denotes the maximum element of the array nums1, and min(nums2) denotes the minimum element of the array nums2.

Return the integer denoting the value of such partition.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,3,2,4]
Output: 1
💡 Note: Sort to get [1,2,3,4]. Best partition is [1] and [2,3,4] giving |1-2| = 1, or [1,2] and [3,4] giving |2-3| = 1.
Example 2 — All Same Elements
$ Input: nums = [100,1,10]
Output: 9
💡 Note: Sort to get [1,10,100]. Check splits: |1-10| = 9, |10-100| = 90. Minimum is 9.
Example 3 — Two Elements
$ Input: nums = [1,1]
Output: 0
💡 Note: Only one way to partition: nums1=[1], nums2=[1]. Value is |1-1| = 0.

Constraints

  • 2 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Find the Value of the Partition INPUT nums = [1, 3, 2, 4] 1 3 2 4 i=0 i=1 i=2 i=3 Goal: Partition into nums1, nums2 Minimize |max(nums1) - min(nums2)| Partition Value Formula: |max(nums1) - min(nums2)| Both arrays must be non-empty Each element in exactly one array ALGORITHM STEPS 1 Sort the Array [1,3,2,4] --> [1,2,3,4] 1 2 3 4 2 Find Adjacent Differences Compare consecutive elements 2-1=1 3-2=1 4-3=1 3 Find Minimum Difference min(1, 1, 1) = 1 4 Optimal Partition Split between adjacent pair nums1=[1,2] nums2=[3,4] Time: O(n log n) | Space: O(1) FINAL RESULT Optimal Partition Found: nums1 [1, 2] nums2 [3, 4] Calculation: max(nums1) = 2 min(nums2) = 3 |2 - 3| = 1 OUTPUT 1 OK - Minimum partition value achieved with adjacent split Key Insight: After sorting, the optimal partition is always between two adjacent elements. The minimum difference between adjacent elements in sorted array gives the answer. This is because max(nums1) will be one element and min(nums2) will be its neighbor in sorted order. TutorialsPoint - Find the Value of the Partition | Optimal Solution
Asked in
Google 15 Microsoft 12 Amazon 8
22.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen