Skip to content

2294. Partition Array Such That Maximum Difference Is K 👍

  • Time: $O(\texttt{sort})$
  • Space: $O(\texttt{sort})$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  int partitionArray(vector<int>& nums, int k) {
    ranges::sort(nums);

    int ans = 1;
    int min = nums[0];

    for (int i = 1; i < nums.size(); ++i)
      if (min + k < nums[i]) {
        ++ans;
        min = nums[i];
      }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public int partitionArray(int[] nums, int k) {
    Arrays.sort(nums);

    int ans = 1;
    int min = nums[0];

    for (int i = 1; i < nums.length; ++i)
      if (min + k < nums[i]) {
        ++ans;
        min = nums[i];
      }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def partitionArray(self, nums: List[int], k: int) -> int:
    nums.sort()

    ans = 1
    min = nums[0]

    for i in range(1, len(nums)):
      if min + k < nums[i]:
        ans += 1
        min = nums[i]

    return ans