Problem Statement
Partition Array Such That Maximum Difference Is K - LeetCode Contest
Pattern: Pattern Sliding Window
Solution
public int partitionArray(int[] nums, int k) {
if (nums.length == 1) return 1;
// sort array
Arrays.sort(nums);
int start = 0, end = 1, subArrayCount = 1;
// sliding window
while(end < nums.length){
// if max-min > k
if(nums[end]-nums[start] > k) {
// reset start
start = end;
// increment count
subArrayCount++;
}
end++;
}
return subArrayCount;
}
Notes
- Sort array
- increase window size till
nums[end]-num[start] > k
- reset window and increment
subarrayCount
- reset window and increment