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 mn = nums[0];

    for (int i = 1; i < nums.size(); ++i)
      if (mn + k < nums[i]) {
        ++ans;
        mn = 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 mn = nums[0];

    for (int i = 1; i < nums.length; ++i)
      if (mn + k < nums[i]) {
        ++ans;
        mn = 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
    mn = nums[0]

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

    return ans