Input: nums =[1,3,2,4]Output: 1Explanation: We can partition the array nums into nums1 =[1,2] and nums2 =[3,4].- The maximum element of the array nums1 is equal to 2.- The minimum element of the array nums2 is equal to 3.The value of the partition is|2-3|=1.It can be proven that 1is the minimum value out of all partitions.
Input: nums =[100,1,10]Output: 9Explanation: We can partition the array nums into nums1 =[10] and nums2 =[100,1].- The maximum element of the array nums1 is equal to 10.- The minimum element of the array nums2 is equal to 1.The value of the partition is|10-1|=9.It can be proven that 9is the minimum value out of all partitions.
To minimize the value |max(nums1) - min(nums2)|, we want max(nums1) and min(nums2) to be as close as possible. If we sort the array, the optimal partition is between two consecutive elements with the smallest difference.
classSolution {
public:int findValueOfPartition(vector<int>& nums) {
sort(nums.begin(), nums.end());
int ans = INT_MAX;
for (int i =0; i +1< nums.size(); ++i) {
ans = min(ans, nums[i+1] - nums[i]);
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
funcfindValueOfPartition(nums []int) int {
sort.Ints(nums)
ans:=1<<31-1fori:=0; i+1 < len(nums); i++ {
ifnums[i+1]-nums[i] < ans {
ans = nums[i+1] -nums[i]
}
}
returnans}
1
2
3
4
5
6
7
8
9
10
classSolution {
publicintfindValueOfPartition(int[] nums) {
Arrays.sort(nums);
int ans = Integer.MAX_VALUE;
for (int i = 0; i + 1 < nums.length; ++i) {
ans = Math.min(ans, nums[i+1]- nums[i]);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
classSolution {
funfindValueOfPartition(nums: IntArray): Int {
nums.sort()
var ans = Int.MAX_VALUE
for (i in0 until nums.size - 1) {
ans = minOf(ans, nums[i+1] - nums[i])
}
return ans
}
}
1
2
3
4
classSolution:
deffindValueOfPartition(self, nums: list[int]) -> int:
nums.sort()
return min(nums[i+1] - nums[i] for i in range(len(nums)-1))
1
2
3
4
5
6
7
8
9
10
11
impl Solution {
pubfnfind_value_of_partition(nums: Vec<i32>) -> i32 {
letmut nums = nums;
nums.sort();
letmut ans =i32::MAX;
for i in0..nums.len()-1 {
ans = ans.min(nums[i+1] - nums[i]);
}
ans
}
}