greedy December 10, 2022

Partition array such that maximum difference is k

Time O(nlog(n)) Space O(1) Open original problem

We will sort the array and then we will iterate through the array and we will check if the difference between the current element and the previous element is greater than k, if it is, then we increate the result count by 1.

class Solution:
    def partitionArray(self, nums: List[int], k: int) -> int:
        nums.sort()
        curMin, res = nums[0], 0
        for num in nums:
            if num-curMin > k:
                res += 1
                curMin = num
        return res+1

Time complexity: O(nlog(n))
Space complexity: O(1)